I need some help with trying to get the position of the notepad window. I'm pretty sure I need to use the GetWindowRect
function, which is below, but I do not know how to use it. I've put what is below in to a win form project, but myRect.X
, myRect.Y
, etc. did not have anything in them. I though they should've at least had the x, y, width, height, of the winform I was working in. But it always displayed 0. honestly I just don't understand how to use this. Ive looked around for a 5ish hours now. but haven't learned anything.
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(HandleRef hWnd, out RECT lpRect);
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int Left; // x position of upper-left corner
public int Top; // y position of upper-left corner
public int Right; // x position of lower-right corner
public int Bottom; // y position of lower-right corner
}
Rectangle myRect = new Rectangle();
private void button1_Click(object sender, System.EventArgs e)
{
RECT rct;
if(!GetWindowRect(new HandleRef(this, this.Handle), out rct ))
{
MessageBox.Show("ERROR");
return;
}
MessageBox.Show( rct.ToString() );
myRect.X = rct.Left;
myRect.Y = rct.Top;
myRect.Width = rct.Right - rct.Left + 1;
myRect.Height = rct.Bottom - rct.Top + 1;
}
I’ve also tried the code below, but still the most I got out of this is DrawingBasicShapes.Form1+Rect
located in the NotepadRect
.
Then there is true in the GetWindowRect(ptr, ref NotepadRect)
. I used MessageBox.Show(Convert.ToString(NotepadRect));
to get what was inside.. Same for the other, I’m thinking that was wrong. But I do not know how to show what’s in it.
I was expecting numbers or something to be in here but I guess not. I’m sorry if this is a novice question, or if the answer is clear to you. But I normally do not work with dll import. So I am slowly learning how to use it...
[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);
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));