Sibber.WindowMessageMonitor

NuGet Version License

A class that lets you listen to window messages for a given window, forked from dotMorten/WinUIEx.Messaging.WindowMessageMonitor.

Documentation

See full documentation and API reference at sibber5.github.io/Sibber.WindowMessageMonitor.

Usage

Important

You must create the WindowMessageMonitor on the same thread as the window it would monitor was created on (for CreateWithMessageOnlyWindow, it must be created on a thread with a message pump).
Disposal, however, is thread-safe and can be done from any thread. Make sure to dispose of it when you are done using it, not doing so may cause problems such as memory leaks.

Note

On .NET 8+, this library is compatible with trimming and Native AOT.

If you have an existing window:

var monitor = new WindowMessageMonitor(windowHandle);
monitor.WindowMessageReceived += (object sender, ref WindowMessageEventArgs e) =>
{
    Debug.WriteLine($"Received message: {e.MessageType} with wParam: {e.Message.WParam} and LParam: {e.Message.LParam}");

    // note that `e` is a mutable struct that is passed by reference.
    e.Handled = true;
    e.Result = 1;
}

Or you can create a message-only window:

var monitor = WindowMessageMonitor.CreateWithMessageOnlyWindow();

Make sure to dispose when you're done using the instance:

monitor.Dispose();

Or use monitor.Free() which does the exact same thing as Dispose() but throws if an error occurs, so you can log it.

Note

Subscribers to WindowMessageReceived should catch and handle all exceptions. If that is not possible, you can subscribe to WindowMessageException to handle the thrown exceptions, which would otherwise be swallowed.

The interface IWindowMessageMonitor is also provided in case you want to provide custom implementations, useful for things like other libraries that use this library.

License

The file src/WindowMessageMonitor.cs was taken from dotMorten/WinUIEx, MIT License - Copyright (c) 2021 Morten Nielsen. See the license notice at the top of the file for more info.

The rest of the library/repository is licensed under the MIT License - see LICENSE - unless otherwise stated in specific files or sections. See individual files for exceptions.