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

How can I get the title of the window that the user is currently focused on? I am making a program that starts with another window, and if the user is not focused on this window, I can not find a reason to update my program.

So, how can I determine in which window the user is focused?

I tried to peek into

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

but I seem to be able to use this only if Window is part of my application, and it is not.

+4
source share
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;
}
+8
source

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

Source: https://habr.com/ru/post/1610382/


All Articles