Question

I am attempting to write a program that considers Screen Bounds and if a window spans multiple screens, the window will "snap" to the closest edge of the Screen which the window has the most area in.

[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetWindowRect(IntPtr hWnd, ref Rectangle lpRect);

Rectangle rct = new Rectangle();
GetWindowRect(hwnd, ref rct);

if (rct.IntersectsWith(Screen.AllScreens[0].Bounds))
{
    Rectangle hwndinterwithscreen = Rectangle.Intersect(rct, Screen.AllScreens[0].Bounds);
    MessageBox.Show("hwnd: " + hwnd.ToInt32().ToString() + " intersects with: " + Screen.AllScreens[0].DeviceName + " at: " + hwndinterwithscreen.Location + " that is this big: " + hwndinterwithscreen.Size);
}
}

With the above, I am seeing very strange results: 1) If the center of the top message bar is moved off Screen.AllScreens[0], but still overlaps with Screen.AllScreens[0], the conditional isn't entered. 2) hwndinterwithscreen.Size changes every time I move the window, and seems to be consider the closest border of Screen.AllScreens[0] in the hwndinterwithscreen calculation.

Unless I am misunderstanding what is very clear documentation on System.Drawing.Rectangle.Intersect(), something is abnormal.

Why is hwndinterwithscreen.Size reporting different numbers.

Était-ce utile?

La solution

You used the wrong structure Rectangle in the GetWindowRect function, you have to use the RECT structure which can be defined like this:

public struct RECT {
   public int left, top, right, bottom;
}

However, to get the Screen in which the window has the most intersection, you can try using the static method Screen.FromControl:

Screen scr = Screen.FromControl(yourForm);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top