30/09/2014 by Nitesh

How To List The Name of Current Active Window in C#

Friends,

In this post, we will see how can we get the name of currently active window using C#. Since a .Net application cannot access objects outside the application, to get the active window we will use few functions of Windows API provided by Microsoft. We will specifically use GetForegroundWindow() and GetWindowText() functions to implement this functionality.

To get started, we will import the following namespaces in our application –

using System.Text;
using System.Runtime.InteropServices;

In the class, we will declare the prototype of Windows API functions as below –

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

[DllImport("user32.dll")]
static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);

Finally we write a function that will print the name of current running window in the following function –

private void GetActiveWindow()
{
    const int nChars = 256;
    IntPtr handle;
    StringBuilder Buff = new StringBuilder(nChars);

    handle = GetForegroundWindow();
            
    if (GetWindowText(handle, Buff, nChars) > 0)
    {
       Console.WriteLine(Buff.ToString());
    }
}

Now you can call this function at any given place in your application. This will print the currently active window on your system.

Hope you like this! Keep learning and sharing! Cheers!

#.Net#C##How To?#Utilities#Windows API#Winforms