如何激活不属于我的应用程序的 window?

How to get active window that is not part of my application?

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

那么我如何确定 window 用户关注的是什么?

我确实尝试调查过

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

但我似乎只能在 Window 是我的应用程序的一部分时使用它,但事实并非如此。

使用GetForegroundWindow to retrieve the handle of the focused window and GetWindowText获得window称号。

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

检查此代码:

[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;
}