1

我目前正在编写一个应用程序,该应用程序需要捕获用户在其窗口句柄上所做的每个操作。

我需要引发以下事件:

  • 窗口调整大小、最大化、最小化或移动
  • 用户更改了活动窗口
  • 用户更改了窗口句柄的键盘焦点

为此,我尝试了很多解决方案,但徒劳无功。首先,我使用了一个计时器,它每 100 毫秒轮询一次前台窗口(使用GetForegroundWindow() )和使用AttachThreadInput()加上GetFocus()函数的键盘聚焦句柄。

但是这个解决方案不是很方便,我更喜欢使用 .NET Framework 提供的 UIAutomation 的更简洁的解决方案。但是我意识到它使用了大量的 CPU 并且对于我的目的来说太慢了,当我切换到另一个窗口句柄时,有时会调用该事件 3 或 4 次。

关于窗口调整大小、最大化等。我也做了一个计时器(但不是很真实),并尝试使用一些 Hooking 技术,如 CBT 钩子和 Shell 钩子。不幸的是,我发现 C# 不支持这种钩子(全局钩子)。

我正在为我的程序的这一部分寻找稳定可靠的代码。提前致谢。

4

1 回答 1

1

BrendanMcK wonderfully respond to my question on this post:

Setting up Hook on Windows messages

I copied his answer just below. It is more convenient than Timer as I suggered, and it is less CPU-eater than UIAutomation. Thanks everyone!

using System;
using System.Windows;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class NameChangeTracker
{
    delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType,
        IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);

    [DllImport("user32.dll")]
    static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr
       hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess,
       uint idThread, uint dwFlags);

    [DllImport("user32.dll")]
    static extern bool UnhookWinEvent(IntPtr hWinEventHook);

    const uint EVENT_OBJECT_NAMECHANGE = 0x800C;
    const uint WINEVENT_OUTOFCONTEXT = 0;

    // Need to ensure delegate is not collected while we're using it,
    // storing it in a class field is simplest way to do this.
    static WinEventDelegate procDelegate = new WinEventDelegate(WinEventProc);

    public static void Main()
    {
        // Listen for name change changes across all processes/threads on current desktop...
        IntPtr hhook = SetWinEventHook(EVENT_OBJECT_NAMECHANGE, EVENT_OBJECT_NAMECHANGE, IntPtr.Zero,
                procDelegate, 0, 0, WINEVENT_OUTOFCONTEXT);

        // MessageBox provides the necessary mesage loop that SetWinEventHook requires.
        // In real-world code, use a regular message loop (GetMessage/TranslateMessage/
        // DispatchMessage etc or equivalent.)
        MessageBox.Show("Tracking name changes on HWNDs, close message box to exit.");

        UnhookWinEvent(hhook);
    }

    static void WinEventProc(IntPtr hWinEventHook, uint eventType,
        IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
    {
        // filter out non-HWND namechanges... (eg. items within a listbox)
        if(idObject != 0 || idChild != 0)
        {
            return;
        }
        Console.WriteLine("Text of hwnd changed {0:x8}", hwnd.ToInt32()); 
    }
}
于 2013-07-17T09:52:38.003 回答