Quantcast
Channel: Chui's Counterpoint » WPF
Viewing all articles
Browse latest Browse all 8

Creating a Message Only window using WPF

$
0
0

Classic Win32 applications use a Window as basic unit of abstraction, including using it for Inter Process Communication. For example, a message only window is hidden, and we only listen to to for messages that are posted from elsewhere. To create a message only window, it must have its parent HWND set to HWND_MESSAGE (i.e. IntPtr(-3)). Then custom messages can be sent as long as the message id falls within the bounds specified here.

While WPF does away with Windows, the interop library provides the basic building blocks for us to create Win32 windows.

/// <summary>
///     Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    private readonly IntPtr _sourceHandle;

    // Valid ranges here:
    // https://msdn.microsoft.com/en-us/library/windows/desktop/ms644927(v=vs.85).aspx#app_defined
    private const uint CustomMessage = 0x8801; 

    public MainWindow()
    {
        InitializeComponent();

        _sourceHandle = CreateMessageOnlyWindow();
        Button1.Click += SendMessageToMessageOnlyWindow;
    }

    private IntPtr CreateMessageOnlyWindow()
    {
        IntPtr HWND_MESSAGE = new IntPtr(-3);
        var source =
            new HwndSource(new HwndSourceParameters() { ParentWindow = HWND_MESSAGE});
        source.AddHook(WndProc);
        return source.Handle;
    }

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled)
    {
        if (msg == CustomMessage)
        {
            Button1.Dispatcher.Invoke(
                new Action(delegate { Button1.Content = lparam.ToInt32().ToString(); }));
                
            handled = true;

            return new IntPtr(20);
        }
        return IntPtr.Zero;
    }

    private void SendMessageToMessageOnlyWindow(object sender, RoutedEventArgs e)
    {
        var result = SendMessage(_sourceHandle, CustomMessage, IntPtr.Zero, new IntPtr(DateTime.Now.Second));
        Contract.Assert(result.ToInt32() == 20);
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
}

The post Creating a Message Only window using WPF appeared first on Chui's Counterpoint.


Viewing all articles
Browse latest Browse all 8

Latest Images

Trending Articles





Latest Images