天天看點

WPF擷取視窗句柄的方法

原文: WPF擷取視窗句柄的方法 通過WPF的互操作幫助類WindowInteropHelper,相關連接配接: https://msdn.microsoft.com/zh-cn/library/system.windows.interop.windowinterophelper.aspx

public MainWindow()
        {
            InitializeComponent();
           
            this.SourceInitialized += MainWindow_SourceInitialized;
        }

        private void MainWindow_SourceInitialized(object sender, System.EventArgs e)
        {
            var handle = (new WindowInteropHelper(this)).Handle;
        }           

可以使用HwndSource.AddHook(HwndSourceHook)加一個事件處理程式接收所有視窗消息,相關連接配接:

https://msdn.microsoft.com/zh-cn/library/system.windows.interop.hwndsource.aspx
private void MainWindow_SourceInitialized(object sender, System.EventArgs e)
        {
            var handle = (new WindowInteropHelper(this)).Handle;
            HwndSource.FromHwnd(handle).AddHook(new HwndSourceHook(WndProc));
        }

        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            throw new NotImplementedException();
        }