在控制台应用程序中更改时尝试读取活动的 window 标题

Trying to read the active window title when it changes in Console Application

我正在尝试制作一个程序,当它更改为控制台 window 时,它会写入活动的 window 标题。

这是我的代码,它可以在 winform 应用程序中运行,但不能在控制台应用程序中运行,我不知道哪里出了问题。
任何帮助将不胜感激。

class Program
{
    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);

    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)
    {
        Console.WriteLine(GetActiveWindowTitle() + "\r\n");
    }

    static void Main(string[] args)
    {
        WinEventDelegate dele = null;

        Program a = new Program();
        dele = new WinEventDelegate(a.WinEventProc);
        IntPtr m_hhook = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);



        Console.ReadKey();
    }
 }

"The client thread that calls SetWinEventHook must have a message loop in order to receive events." 控制台应用程序中的线程没有消息循环。除非你建造一个:

using System.ComponentModel;
using System.Windows.Forms;

...

[DllImport("user32.dll", SetLastError = true)]
static extern int GetMessage(out Message lpMsg, IntPtr hwnd, int wMsgFilterMin, int wMsgFilterMax);

[DllImport("user32.dll")]
static extern int TranslateMessage(Message lpMsg);

[DllImport("user32.dll")]
static extern int DispatchMessage(Message lpMsg);

然后将Console.ReadKey()替换为

Message msg;
while (true) { 
    int result = GetMessage(out msg, IntPtr.Zero, 0, 0);
    if (result == 0) break;
    if (result == -1) throw new Win32Exception();
    TranslateMessage(msg);
    DispatchMessage(msg);
}

我很懒,从 System.Windows.Forms 中获取了 Message 结构。如果你不想依赖,你可以单独添加它的定义。

由于此线程现在正忙于处理消息,如果您想进行其他处理,您可能希望在单独的专用线程上执行此操作。