Search code examples
c#wpfwndproc

How to handle WndProc messages in WPF?


In Windows Forms, I'd just override WndProc, and start handling messages as they came in.

Can someone show me an example of how to achieve the same thing in WPF?


Solution

  • Actually, as far as I understand such a thing is indeed possible in WPF using HwndSource and HwndSourceHook. See this thread on MSDN as an example. (Relevant code included below)

    // 'this' is a Window
    HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
    source.AddHook(new HwndSourceHook(WndProc));
    
    private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        //  do stuff
    
        return IntPtr.Zero;
    }
    

    Now, I'm not quite sure why you'd want to handle Windows Messaging messages in a WPF application (unless it's the most obvious form of interop for working with another WinForms app). The design ideology and the nature of the API is very different in WPF from WinForms, so I would suggest you just familiarise yourself with WPF more to see exactly why there is no equivalent of WndProc.