Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 238
Joakim Carlsson Avatar asked Oct 06 '15 08:10

Joakim Carlsson


2 Answers

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;
}
like image 191
Nikita Shrivastava Avatar answered Oct 21 '22 05:10

Nikita Shrivastava


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) ; 
} 
like image 23
Perfect28 Avatar answered Oct 21 '22 06:10

Perfect28