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

时间:2013-08-04 10:05:28

标签: c# .net winapi hook

我使用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;
    }

1 个答案:

答案 0 :(得分:1)

我将NativeWindow更改为Form,它现在看起来像是在工作。伙计们,请让我知道你的想法。