How to Get and Set the Window Position of Another Application in C#

How to get and set the window position of another application in C#

I actually wrote an open source DLL just for this sort of thing.
Download Here

This will allow you to find, enumerate, resize, reposition, or do whatever you want to other application windows and their controls.
There is also added functionality to read and write the values/text of the windows/controls and do click events on them. It was basically written to do screen scraping with - but all the source code is included so everything you want to do with the windows is included there.

How to get window's position?

Try this:

[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindow(string strClassName, string strWindowName);

[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hwnd, ref Rect rectangle);

public struct Rect {
public int Left { get; set; }
public int Top { get; set; }
public int Right { get; set; }
public int Bottom { get; set; }
}

Process[] processes = Process.GetProcessesByName("notepad");
Process lol = processes[0];
IntPtr ptr = lol.MainWindowHandle;
Rect NotepadRect = new Rect();
GetWindowRect(ptr, ref NotepadRect);

Getting the position of a windows application from C#

If all you are putting in your messagebox is the Rect object itself, that's exactly what output you're going to get.

Output your messagebox as follows:

MessageBox.Show( string.Format("Left: {0}\r\nTop: {1}\r\nRight: {2}\r\nBottom: {3}", NotepadRect.Left, NotepadRect.Top, NotepadRect.Right, NotepadRect.Bottom));

How do you set a cursor's position in a different window/application?

Sending RAW Input data to use mouse. Some applications read raw mouse strokes while others read virtual mouse strokes.

int to_x = 500;
int to_y = 300;
int screenWidth = InternalGetSystemMetrics(0);
screenHeight = InternalGetSystemMetrics(1);
// Mickey X coordinate
int mic_x = (int)System.Math.Round(to_x * 65536.0 / screenWidth);
// Mickey Y coordinate
int mic_y = (int)System.Math.Round(to_y * 65536.0 / screenHeight);
// 0x0001 | 0x8000: Move + Absolute position
Mouse_Event(0x0001 | 0x8000, mic_x, mic_y, 0, 0);
// 0x0002: Left button down
Mouse_Event(0x0002, mic_x, mic_y, 0, 0);
// 0x0004: Left button up
Mouse_Event(0x0004, mic_x, mic_y, 0, 0);```

How do I find the position / location of a window given a hWnd without NativeMethods?

I just went through this on a project and was unable to find any managed C# way.

To add to Reed's answer the P/Invoke code is:

 [DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
private struct RECT
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}

Call it as:

  RECT rct = new RECT();
GetWindowRect(hWnd, ref rct);


Related Topics



Leave a reply



Submit