Click here to Skip to main content
15,899,314 members
Articles / Programming Languages / C#

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

Rate me:
Please Sign up or sign in to vote.
4.71/5 (8 votes)
30 Sep 2014CPOL 27.3K   13   2
How to list the name of the current active window in C#

In this post, we will see how we can 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:

C#
using System.Text;
using System.Runtime.InteropServices;

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

C#
[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:

C#
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!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder Rebin Infotech
India India
A passionate developer with over 10 years of experience and building my software company code by code. Experience withMS Technologies like .Net | MVC | Xamarin | Sharepoint | MS Project Server and PhP along with open source CMS Systems like Wordpress/DotNetNuke etc.

Love to debug problems and solve them. I love writing articles on my website in my spare time. Please visit my Website for more details and subscribe to get technology related tips/tricks. #SOreadytohelp

Comments and Discussions

 
GeneralMy vote of 3 Pin
Member 95425322-Oct-14 8:28
Member 95425322-Oct-14 8:28 
GeneralRe: My vote of 3 Pin
Nitesh Kejriwal3-Oct-14 1:10
professionalNitesh Kejriwal3-Oct-14 1:10 
Please let me know how can I improve this article so that you can give my article a rating of 5 Smile | :)
Nitesh K Luharuka
Consultant
http://www.niteshluharuka.com

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.