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

时间:2015-10-06 08:36:51

标签: c# .net pinvoke

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.

2 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分:1)

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