How do I get the title of the current active window using c#?


Question

I'd like to know how to grab the Window title of the current active window (i.e. the one that has focus) using C#.

1
106
2/20/2011 1:28:03 PM

Accepted Answer

See example on how you can do this with full source code here:

http://www.csharphelp.com/2006/08/get-current-window-handle-and-caption-with-windows-api-in-c/

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

Edited with @Doug McClean comments for better correctness.

160
12/23/2013 2:42:56 AM

If you were talking about WPF then use:

 Application.Current.Windows.OfType<Window>().SingleOrDefault(w => w.IsActive);

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon