In Windows Forms, I'd just override WndProc
, and start handling messages as they came in.
Can someone show me an example of how to achieve the same thing in WPF?
You can do this via the System.Windows.Interop
namespace which contains a class named HwndSource
.
Example of using this
using System;
using System.Windows;
using System.Windows.Interop;
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
source.AddHook(WndProc);
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
// Handle messages...
return IntPtr.Zero;
}
}
}
Completely taken from the excellent blog post: Using a custom WndProc in WPF apps by Steve Rands