Skip to content

Instantly share code, notes, and snippets.

@Const-me
Created June 18, 2019 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Const-me/afe65d5205843824bcca046545b021bd to your computer and use it in GitHub Desktop.
Save Const-me/afe65d5205843824bcca046545b021bd to your computer and use it in GitHub Desktop.
Subclassing WPF window to handle custom messages
using System;
using System.Windows;
using System.Windows.Interop;
static class SubclassWindow
{
// Call this from the constructor of your main window. SourceInitialized event is raised long after the constructor.
public static void initialize( Window wnd )
{
wnd.SourceInitialized += ( object sender, EventArgs e ) => sourceInitialized( wnd );
}
static void sourceInitialized( Window window )
{
IntPtr handle = ( new WindowInteropHelper( window ) ).Handle;
HwndSource.FromHwnd( handle ).AddHook( new HwndSourceHook( windowProcHook ) );
}
static IntPtr windowProcHook( IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled )
{
// Call C++ DLL here. Set handled to true if that window message was handled by the C++ code.
if( interop.handleWindowMessage( hwnd, msg, wParam, lParam ) )
handled = true;
return IntPtr.Zero;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment