September 30, 2014 by Nitesh

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


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 –

static extern IntPtr GetForegroundWindow();

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)

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

Support us!

If you like this site please help and make click on any of these buttons!

Powered by WordPress Popup