简体   繁体   English

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

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

How can I get the Window Title that the user currently have focus on? 如何获得用户当前关注的窗口标题? I'm making a program that runs with another Window, and if the user does not have focus on that window I find no reason for my program to keep updating. 我正在制作一个与另一个Window一起运行的程序,如果用户没有将注意力集中在该窗口上,则我的程序没有理由继续更新。

So how can I determine what window the user have focus on? 那么,如何确定用户关注的窗口呢?

I did try to look into 我确实尝试研究

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

but I seems I can only use that if the Window is part of my application which is it not. 但是我似乎只能在Window是我的应用程序的一部分的情况下使用它,而事实并非如此。

Check this code: 检查此代码:

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

Use GetForegroundWindow to retrieve the handle of the focused window and GetWindowText to get the window title. 使用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) ; 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM