How to handle WndProc messages in WPF?

Shuft picture Shuft · Mar 8, 2009 · Viewed 95.7k times · Source

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?

Answer

Robert MacLean picture Robert MacLean · Dec 18, 2009

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