我想获取 C# 控制台应用程序中当前活动窗口的标题字符串。
我的下面的代码就是这样做的。然而,只有当我逐行缓慢地调试代码时,它才有效。当我刚开始运行时,
while
似乎进入了无限循环。然而,如果没有 while
循环,首先就找不到窗口标题(因此不会写入控制台)。
怎么了?以及如何解决?
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, System.Text.StringBuilder text, int count);
static void Main(string[] args)
{
IntPtr handle = GetForegroundWindow();
const int nChars = 256;
System.Text.StringBuilder Buff = new System.Text.StringBuilder(nChars);
while (GetWindowText(handle, Buff, nChars) <= 0)
{
// Wait until GetWindowText returns a positive value
}
Console.WriteLine(Buff.ToString());
}
}
很可能在程序开始时没有活动窗口,或者当您询问其文本时它可能会关闭。这就是为什么我们要这样做:
// note that we ask for foreground window
while (GetWindowText(GetForegroundWindow(), Buff, nChars) <= 0) {
// Let other threads run if we still don't have foreground window
Thread.Yield();
}