如何获取不属于我的应用程序的活动窗口?

如何获取用户当前关注的窗口标题? 我正在制作一个与另一个Window一起运行的程序,如果用户没有关注该窗口,我发现我的程序没有理由继续更新。

那么如何确定用户关注的窗口?

我确实试着去研究一下

[DllImport("user32.dll")] static extern IntPtr GetActiveWindow(); 

但我似乎只能使用它,如果Window是我的应用程序的一部分,它不是。

检查此代码:

 [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; StringBuilder Buff = new StringBuilder(nChars); IntPtr handle = GetForegroundWindow(); if (GetWindowText(handle, Buff, nChars) > 0) { return Buff.ToString(); } return null; } 

使用GetForegroundWindow检索焦点窗口的句柄,使用GetWindowText获取窗口标题。

 [ DllImport("user32.dll") ] static extern int GetForegroundWindow(); [ DllImport("user32.dll") ] static extern int GetWindowText(int hWnd, StringBuilder text, int count); static void Main() { StringBuilder builder = new StringBuilder(255) ; GetWindowText(GetForegroundWindow(), builder, 255) ; Console.WriteLine(builder) ; }