且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF获取窗口句柄的方法

更新时间:2022-09-18 13:26:26

原文: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();
        }