Friday, January 23, 2009

How to get the HWND and hook into the WndProc of a WPF application

I've written a quick sample which hooks into the WM_ messages and displays them real-time. It looks like this:



This is the code that does the work:

private void Window1_Loaded(object sender, RoutedEventArgs e)
{
    // do this to get the HWND and set up the window hook
    WindowInteropHelper helper = new WindowInteropHelper(this);
    HwndSource.FromHwnd(helper.Handle).AddHook(HwndSourceHookHandler);
}

private IntPtr HwndSourceHookHandler(IntPtr hwnd, int msg, IntPtr wParam, 
    IntPtr lParam, ref bool handled)
{
    // this is the window hook handler
}

Download sample app with source code

2 comments:

Kevin Westhead said...

Nice, but I think you should be using the OnSourceInitialized override to retrieve the HwndSource. This usually occurs before the Loaded event is fired but just in case there are some scenarios where it isn't, using OnSourceInitialized will more reliable.

Dan Lamping said...

Thanks for the feedback, whoever you are. You're right - that would be a good change. I'll update the code when I get the chance.

Dan