How to handle WndProc messages in WPF?

前端 未结 9 1099
不知归路
不知归路 2020-11-22 10:46

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 thi

9条回答
  •  遥遥无期
    2020-11-22 11:00

    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

提交回复
热议问题