试图读取活动窗口标题时,它在控制台应用程序中更改

本文关键字:控制台 应用程序 读取 活动 窗口标题 | 更新日期: 2023-09-27 18:09:17

我正试图编写一个程序,写入活动窗口标题,每当它改变到控制台窗口。

这是我的代码,它可以在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();
    }
 }

试图读取活动窗口标题时,它在控制台应用程序中更改

"调用SetWinEventHook的客户端线程必须有一个消息循环才能接收事件。"控制台应用程序中的线程没有消息循环。除非你自己建一个:

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.FormsMessage结构。如果你不想接受依赖关系,你可以单独添加它的定义。

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