- Posted by Admin on January 20, 2009
If you need to get the caption text of currently active window, it is very easy to get using C#. You just need to use built-in windows DLL named user32.dll.
Here is the class that captures the caption text of currently active window.
public static class ActiveWindowForm
{
//
Declare external functions.
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern int GetWindowText(IntPtr
hWnd, StringBuilder text, int count);
public static string
GetActiveWindowText()
{
int
chars = 256;
StringBuilder
buff = new StringBuilder(chars);
IntPtr
handle = GetForegroundWindow();
if
(GetWindowText(handle, buff, chars) > 0)
{
return
(buff.ToString()); // + " " +
handle.ToString());
}
else
{
return
"";
}
};
As the function that captures active window text is made static. You can use the below code to get the active window text anywhere in your windows application being developed.
string windowname;
windowname = ActiveWindowForm.GetActiveWindowText();
That's it. Hope this helps!