【问题标题】:Hook to receive window created and destroyed notification挂钩接收窗口创建和销毁通知
【发布时间】:2023-04-03 19:50:01
【问题描述】:

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

【问题讨论】:

  • 邮政编码,会有帮助的
  • 你在创建一个shell扩展吗?你在调用RegisterShellHookWindow 函数吗?您是否正在检查您调用的所有函数的返回码是否有错误?
  • 我没有创建外壳扩展。我只是想做一个任务栏,因为我需要窗口创建和销毁的通知,所以我调用了 RegisterShellHookWindow 函数。但有趣的部分是我在调试时收到通知,而不是在我运行应用程序而不调试时收到通知。

标签: c# .net winapi hook


【解决方案1】:

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

【讨论】:

  • 您使用的 API 本质上是私有的,不适合公共使用。文档在顶部相当明确地指出了这一点。如果您考虑函数的名称和描述,也相当清楚:它适用于 shell 窗口。你是贝壳窗吗?不,因为您不在 Windows Shell 团队中。事实上,您甚至没有编写 shell 扩展。所以你真的不应该使用 API。当然,如果必须的话,你将不得不给它一个实际的窗口,至少可以伪装成一个 shell 窗口。
  • 这个应用是一个测试应用。但我的主要应用是一个 shell 窗口 Cody Gray
  • 但是我的 shell 应用程序应该能够在窗口创建和窗口销毁时发送消息,不是吗?到目前为止,我的应用程序还不是一个成熟的 shell 应用程序。那么有什么想法吗?
猜你喜欢
  • 2012-12-25
  • 1970-01-01
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多