| Applies to: | |
| Product | General |
| Platform | Windows |
.Net Classes Used
- WindowInteropHelper : This class is needed to retrieve the handle of the WPF application window.
- HwndSource : The class will provide a method to hook the WndProc of the WPF application.
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 AddHookNOTE: 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




