2

如何正确停止钩子?由于挂钩,我无法正确关闭应用程序。

代码背后:

protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            IntPtr windowHandle = (new WindowInteropHelper(this)).Handle;
            HwndSource src = HwndSource.FromHwnd(windowHandle);
            src.AddHook(new HwndSourceHook(WndProc));
        }

 private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            // Handle WM_DEVICECHANGE
            if (msg == 0x0219)
            {
RunService();
    }

我写了类似下面的东西,但它不会正确停止应用程序:

private void StopHook()
        {
            IntPtr windowHandle = (new WindowInteropHelper(this)).Handle;
            HwndSource src = HwndSource.FromHwnd(windowHandle);
            src.RemoveHook(new HwndSourceHook(this.WndProc));
        }

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            base.OnClosing(e);
            StopService(); // to clear thread
            StopHook();
        }

更新:

我认为 RunService 导致了问题,但我正在使用 StopService 关闭所有线程。

4

0 回答 0