挂钩接收窗口创建和销毁通知

本文关键字:通知 创建 窗口 | 更新日期: 2023-09-27 18:26:12

我使用RegisterWindowMessage("SHELLHOOK")注册窗口创建和销毁事件。我的代码是用C#编写的。当我调试代码时,代码运行得很好。但是,当我在没有调试的情况下运行程序时,我不会像以前在调试时那样收到WndProc消息。Windows会阻止挂钩吗?

class ShellHook:NativeWindow
{
    public ShellHook(IntPtr hWnd)
    {
        if (Win32.RegisterShellHookWindow(this.Handle))
        {
            WM_ShellHook    = Win32.RegisterWindowMessage("SHELLHOOK");
        }
    }
    protected override void WndProc(ref Message m)
    {
        if (m.Msg == WM_ShellHook)
        {
            switch((ShellEvents)m.WParam)
            {
                    //m.lparam
                case ShellEvents.HSHELL_WINDOWCREATED:
                    if (windowCreatedEvent != null)
                    {
                        windowCreatedEvent(m.LParam);
                    }
                    break;
                case ShellEvents.HSHELL_WINDOWDESTROYED:
                    if (windowDestroyedEvent != null)
                    {
                        windowDestroyedEvent(m.LParam);
                    }
                    break;
            }
        }
        base.WndProc(ref m);
    }
}

这就是我启动wpf应用程序的方式。

 public partial class App : Application
 {
    MainWindow mainWindowView;
    public App()
    {
        Startup += new StartupEventHandler(App_Startup);
    }
    void App_Startup(object sender, StartupEventArgs e)
    {
        mainWindowView = new MainWindow();
        MainWindowViewModel mainWindowViewModel = new MainWindowViewModel();
        mainWindowView.DataContext = mainWindowViewModel;
        mainWindowView.ShowDialog();
    }
 }

我的MainWindowViewModel构造函数如下:

 public MainWindowViewModel()
    {
        EnumWindows(new EnumWindowsProc(EnumTheWindows), IntPtr.Zero);
        System.Windows.Forms.Form f = new System.Windows.Forms.Form();
        ShellHook shellHookObject = new ShellHook(f.Handle);
        shellHookObject.windowCreatedEvent += shellHookObject_windowCreatedEvent;
        shellHookObject.windowDestroyedEvent += shellHookObject_windowDestroyedEvent;
    }

挂钩接收窗口创建和销毁通知

我将NativeWindow更改为Form,它现在看起来可以工作了。伙计们,请告诉我你们的想法。