tags:

views:

5900

answers:

8

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#.

A: 

Use the Windows API. Call GetForegroundWindow().

GetForegroundWindow() will give you a handle (named hWnd) to the active window.

Documentation: http://msdn.microsoft.com/en-us/library/ms633505(VS.85).aspx

amdfan
+13  A: 

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

http://www.csharphelp.com/archives2/archive301.html

[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;
    IntPtr handle = IntPtr.Zero;
    StringBuilder Buff = new StringBuilder(nChars);
    handle = GetForegroundWindow();

    if (GetWindowText(handle, Buff, nChars) > 0)
    {
        return Buff.ToString();
    }
    return null;
}


Edited with @Doug McClean comments for better correctness.

smink
Don't forget to be a good citizen. http://blogs.msdn.com/oldnewthing/archive/2007/07/27/4072156.aspx and http://blogs.msdn.com/oldnewthing/archive/2008/10/06/8969399.aspx have relevant info.
Greg D
+5  A: 

I agree with Jorge's answer BUT those ints should be IntPtrs (both for 64-bit-friendliness and so that you can't do math by mistake).

Doug McClean
Agreed. Just updated my answer for better correctness. Thanks.
smink
A: 

I agree with @Jorge and @Doug but only if it's in another application or not in your own appdomain. If you want the current window within your application use Form.ActiveForm (winforms) or Application.Current.MainWindow (WPF) to get the active window. Someone who has used WPF more than me, please comment / edit as to whether there's a better way to get active rather than main window for and application in WPF.

Hamish Smith
A: 

@Hamish, MainWindow returns the application's primary window (the window that determines whether the app continues to run or quits when closed), not its foreground window. The main window never changes (unless explicitly).

+1  A: 

Loop over Application.Current.Windows[] and find the one with IsActive = true.

Wouldn't this only work for the windows in the current .Net application?I think d4nt wants to get the title of the current active window on the desktop, no matter what application it belongs to.
Quagmire
A: 

this should do it:

 Application.Current.Windows.OfType<YourWindowType>().First(P=> P.IsActive == true)
Skvettn
A: 

I just tried Skvettn's solution and it works. Thanks!

Arun
John Saunders