简体   繁体   中英

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.

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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