This time I’ll show how to obtain the size and location of a window. I will be using the WindowFinder class that I introduced in the blog Finding specific windows .
Note that the location is not in relation to it’s parent windows location, it is always the absolute screen position.
using System.Runtime.InteropServices;
using System.Drawing;
using System.Text.RegularExpressions;
using System;
using System.Text;
using System.Globalization;
namespace Getting_window_location_and_size
{
class Program
{
const int WM_GETTEXT = 0x000D ;
const int WM_GETTEXTLENGTH = 0x000E ;
[DllImport("User32.Dll" )]
private static extern void GetClassName (int hWnd, StringBuilder s, int nMaxCount);
[DllImport("User32.dll" )]
private static extern Int32 SendMessage (int hWnd, int Msg, int wParam, StringBuilder lParam);
[DllImport("User32.dll" )]
private static extern Int32 SendMessage (int hWnd, int Msg, int wParam, int lParam);
[DllImport("user32.dll" )]
public static extern long GetWindowRect (int hWnd, ref Rectangle lpRect);
static void Main(string [] args)
{
Finding_specific_windows.WindowFinder wf = new Finding_specific_windows.WindowFinder();
wf.FindWindows(0 , null , new Regex("- (Windows|Microsoft) Internet Explorer" ), new Regex("iexplore" ), new Finding_specific_windows.WindowFinder.FoundWindowCallback(foundWindow));
Console.Read();
}
static bool foundWindow(int handle)
{
Rectangle rect = new Rectangle();
GetWindowRect(handle, ref rect);
Console.WriteLine(rect.ToString());
rect.Width = rect.Width - rect.X;
rect.Height = rect.Height - rect.Y;
Console.WriteLine(rect.ToString());
printWindowInfo(handle);
return true ;
}
private static void printWindowInfo (int handle)
{
StringBuilder sbClass = new StringBuilder(256 );
GetClassName(handle, sbClass, sbClass.Capacity);
int txtLength = SendMessage(handle, WM_GETTEXTLENGTH, 0 , 0 );
StringBuilder sbText = new StringBuilder(txtLength + 1 );
SendMessage(handle, WM_GETTEXT, sbText.Capacity, sbText);
Console.WriteLine("Handle: " + handle);
Console.WriteLine("Class : " + sbClass);
Console.WriteLine("Text : " + sbText);
Console.WriteLine();
}
}
}
And the result:
Mark S. Rasmussen
I'm the CTO at
iPaper where I cuddle with databases, mold code and maintain the overall technical & team responsibility. I'm an avid speaker at user groups & conferences. I love life, motorcycles, photography and all things technical. Say hi on
Twitter , write me an
email or look me up on
LinkedIn .