C# 中的全局 window 挂钩

Global window hook in C#

目前我正在使用以下代码激活 window title-

[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();

[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

效果很好。

现在我想在我的 C# 应用程序中捕获全局活动 window 更改事件。不知道怎么办。

有什么帮助吗?

这是摘自 here-

的完整代码片段
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace ActiveWindowChangeEvent
{
    public partial class Form1 : Form
    {
        delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
        WinEventDelegate dele = null;
        [DllImport("user32.dll")]
        static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
        private const uint WINEVENT_OUTOFCONTEXT = 0;
        private const uint EVENT_SYSTEM_FOREGROUND = 3;

        [DllImport("user32.dll")]
        static extern IntPtr GetForegroundWindow();

        [DllImport("user32.dll")]
        static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
        private string GetActiveWindowTitle()
        {
           const int nChars = 256;
           IntPtr handle = IntPtr.Zero;
           StringBuilder Buff = new StringBuilder(nChars);
           handle = GetForegroundWindow();

           if (GetWindowText(handle, Buff, nChars) > 0)
           {
               return Buff.ToString();
           }
           return null;
       }

        public void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
        {
           Log.Text += GetActiveWindowTitle() + "\r\n";  //Log= RichTextBox
        } 

        public Form1()
        {
           InitializeComponent();
           dele = new WinEventDelegate(WinEventProc);
           IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
        }
    }
}

希望这会有所帮助。