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