Sub Classing a WPF Application’s WndProc

By 42Gears Team
Applies to:
Product General
Platform Windows
With the introduction of Windows Presentation Foundation
.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
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.
Download Source Files

Read more about our products:

“Written with expertise and passion to help you understand the topic better.”

4
42Gears Team – Content Author
Published on: November 12, 2013

Subscribe to our newsletter

Stay updated with the latest news, articles, and resources on enterprise mobility.

Weekly articles
Actionable insights delivered once a week. No noise.
No spam
Your privacy matters. Unsubscribe anytime.