1. Home
  2. How to Sub Class a WPF Application’s WndProc?

How to Sub Class a WPF Application’s WndProc?

KB ID: 42G2009391
Views: 611
Updated: June 2021
Applies to:
ProductGeneral
PlatformWindows

With the introduction of the Windows Presentation Foundation (WPF), developers can now create rich User Interface applications which are preferred by end-users. While developing such applications, sometimes there can be a need to intercept the Windows messages. This can be achieved easily in Win32 and WinForm applications and one would wonder is this possible in WPF as well? The answer to this question is, yes it is possible. This article does exactly that and will explain how to Subclass a WPF application’s WndProc.

.Net Classes Used

  1. WindowInteropHelper : This class is needed to retrieve the handle of the WPF application window.
  2. HwndSource : The class will provide a method to hook the WndProc of the WPF application.

Code Snippet:

private void MainWindowLoaded(object sender, RoutedEventArgs e)

{
HwndSource source = HwndSource.FromHwnd(new WindowInteropHelper(this).Handle);
source.AddHook(new HwndSourceHook(WndProc));
}

private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam,ref bool handled)
{
if(msg==WM_CLOSE)
{
//Avoiding a close event
handled=true;
}
return IntPtr.Zero;
}

In the above Snippet, the WindowInteropHelper class provides the handle to the WPF application window which is passed to the HwndSource class and the AddHook method allows to intercept the Window messages using a WndProc, which is WM_CLOSE in this case

NOTE: The HwndSource object should be created only in the Loaded event of your application because that’s when your WPF application is assigned a Window handle, else the WindowInteropHelper class will return an invalid handle.

Read more about our products: