Martin Nikolaev
Martin Nikolaev

Reputation: 243

How to get window properties of a desktop application

So, I am having an application which is intended to operate with another application autonomously.
Example:

  1. Open application A, which start application B
  2. Click on a button 1 and click on the input text

The problem is that Application B is not mine and I want to automate a button click there. I know that button 1 is located 20px from bottom right corner, but I don't know height and width of the window of application B. Is it possible to get width and height of that window in C#?

Upvotes: 1

Views: 933

Answers (1)

Jane S
Jane S

Reputation: 1487

It sure is. You can use the Windows API to get its handle, then from there get its window properties.

Import the API.

[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}

[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd,ref RECT rect);

Then in your function you can:

IntPtr hWnd;
hWnd = GetWindows.FindWindow(null, "Application Title");
User32.RECT windowRect = new User32.RECT();

User32.GetWindowRect(hWnd,ref windowRect);
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;

Upvotes: 2

Related Questions