C#控制台程序获取活动窗口标题遇无限循环问题排查与修复
问题原因分析
- 你只在程序启动时调用了一次
GetForegroundWindow(),获取的是程序启动瞬间的活动窗口句柄。如果此时活动窗口是控制台自身,且窗口标题尚未完成初始化,GetWindowText会返回0,后续循环里一直复用这个旧句柄,永远拿不到有效标题,陷入死循环。 - 调试时你的注意力在调试器窗口,活动窗口不是控制台,所以能拿到有效句柄和标题,因此调试正常。
修复后的代码
using System; using System.Runtime.InteropServices; using System.Threading; 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) { const int nChars = 256; System.Text.StringBuilder buff = new System.Text.StringBuilder(nChars); // 设置超时时间,避免无限循环 int timeout = 5000; int elapsed = 0; while (elapsed < timeout) { // 每次循环重新获取当前活动窗口句柄 IntPtr handle = GetForegroundWindow(); int result = GetWindowText(handle, buff, nChars); if (result > 0) { Console.WriteLine("当前活动窗口标题: " + buff.ToString()); return; } // 短暂休眠,降低CPU占用 Thread.Sleep(50); elapsed += 50; } Console.WriteLine("超时未获取到有效窗口标题"); } }
关键修复点
- 循环内重新获取句柄:每次循环都调用
GetForegroundWindow(),确保拿到的是实时的当前活动窗口句柄。 - 添加休眠机制:用
Thread.Sleep(50)减少循环频率,避免CPU占用过高。 - 增加超时逻辑:设置超时时间,防止极端情况下程序一直卡住。
内容的提问来源于stack exchange,提问作者Pingui
相关产品推荐
相关产品推荐

