d4nt d4nt - 1 year ago 137
C# Question

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

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

Answer Source

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


static extern IntPtr GetForegroundWindow();

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download