WPF equivalent of Application.AddMessageFilter (Windows Forms) WPF equivalent of Application.AddMessageFilter (Windows Forms) windows windows

WPF equivalent of Application.AddMessageFilter (Windows Forms)


In WPF, you can use ComponentDispatcher.ThreadFilterMessage event.

ComponentDispatcher.ThreadFilterMessage += ComponentDispatcher_ThreadFilterMessage;private void ComponentDispatcher_ThreadFilterMessage(ref MSG msg, ref bool handled){     if (msg.message == 513)//MOUSE_LEFTBUTTON_DOWN     {         //todo     }}


If you want to monitor a window message, you can use HwndSource.AddHook method. The following example shows how to use Hwnd.AddHook method. If you want to monitor a application scope message, you can try to use ComponentDispatcher class.

private void Button_Click(object sender, RoutedEventArgs e){    Window wnd = new Window();    wnd.Loaded += delegate    {        HwndSource source = (HwndSource)PresentationSource.FromDependencyObject(wnd);        source.AddHook(WindowProc);    };    wnd.Show();}private static IntPtr WindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled){}