Login  |  Register
Home | Articles | Downloads | Resources | About
Contact Us | My Resume
   Topics:  ASP.NET  C#  .NET  XML 
File Name: Calling Windows API with C# Example
File Size: 19,314 bytes
Downloaded: 1809 times
Posted by WaheedKhan on Tuesday, April 20, 2004 (PST)
Click here to download this file
This article will show you how to use Windows API function GetForegroundWindow, and GetWindowText to get the current window handle and caption with C# in .NET environment.

This article will show you how to use Windows API function GetForegroundWindow, and GetWindowText with C#.

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.

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

 

Posted Online: http://www.csharphelp.com/archives2/archive301.html

Comments:

thanx
By ? on Friday, March 21, 2008 (PST)
very illustrative, thank u

Reply to this Comment

Add Your Comment

Most Popular Downloads

  • Dynamically create TextBoxes and DropDownList with C# and ASP.NET
    This article will show you how to create TextBoxes and DropDownList dynamically on ASP.NET page and then retrieve user input values from dynamically created controls.

  • Dynamically create Controls in ASP.NET with C#
    This article will show you how to create TextBoxes dynamically on web page and then retrieve user input values from dynamically created TextBoxes “Text” property content value.

  • Dynamically create TextBoxes with C# on Windows Form
    Dynamically create and retrieve TextBoxes data with C# on Windows Form

  •  
     
    Home Articles Downloads Resources About