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

2

6

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.

Melton answered 6/10, 2015 at 8:36 Comment(1)
Did you read the documentation for that function? If so, what part was not clear? If not, why not?Nacred
C
13

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;
}
Contraband answered 6/10, 2015 at 8:41 Comment(2)
Got it working now, thanks. WIll accept it when I can.Melton
Sorry it took so long to accept the answer, done it now.Melton
D
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) ; 
} 
Domineca answered 6/10, 2015 at 8:40 Comment(1)
For some reason this will the lenght of the builder will be 0.Melton

© 2022 - 2024 — McMap. All rights reserved.