Search Forum
(57415 Postings)
Search Site/Articles

Archived Articles
712 Articles

C# Books
C# Consultants
What Is C#?
Download Compiler
Code Archive
Archived Articles
Advertise
Contribute
C# Jobs
Beginners Tutorial
C# Contractors
C# Consulting
Links
C# Manual
Contact Us
Legal

GoDiagram for .NET from Northwoods Software www.nwoods.com


              
Printable Version

Get Current Window Handle and Caption With Windows API In C#
By Waheed Khan

In this article I will show you how to use Windows API function GetForegroundWindow, and GetWindowText.

GetForegroundWindow :

The GetForegroundWindow function returns a handle to the window with which the user is currently working.

GetWindowText:

The GetWindowText function copies the text of the specified window's title bar (if it has one) into a buffer.

For more information's MSDN is the great place for Windows API functions.

Start a new project, add labels, button and timer. Make sure set the timer Enable property to true.

Include these lines at the top

using System.Runtime.InteropServices;

using System.Text;

 

Add following lines to declare API functions, to get the Windows API functions we will have to import "user32.dll" Dlls.

[ DllImport("user32.dll") ]

static extern int GetForegroundWindow();

[ DllImport("user32.dll") ]

static extern int GetWindowText(int hWnd, StringBuilder text, int count);

 

Then, write the code for the function

private void GetActiveWindow()
{

const int nChars = 256;
int handle = 0;
StringBuilder Buff = new StringBuilder(nChars);
   
   handle = GetForegroundWindow();

   if ( GetWindowText(handle, Buff, nChars) > 0 )
   {
   this.captionWindowLabel.Text = Buff.ToString();
   this.IDWindowLabel.Text = handle.ToString();
   }

}

and call GetActiveWindow function within timer function

private void timer1_Tick(object sender, System.EventArgs e)
{
GetActiveWindow();
}

That's all.

After running the application, open a notepad, click on it, and you will get the window caption and handle.

Keep Coding !!!


Download the source code.

source - 12 kb