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:
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!
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