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

时间:2016-09-28 12:16:23

标签: c# delegates console-application

我正在尝试创建一个编写活动窗口标题的程序,只要它改变到控制台窗口。

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

1 个答案:

答案 0 :(得分:0)

"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);
}

我懒惰并从Message获取System.Windows.Forms结构。如果您不想接受依赖,可以单独添加该定义。

由于此线程现在已经处理了处理消息,因此如果要进行其他处理,可能需要在单独的专用线程上执行此操作。