0

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.

brandeded
  • 2,080
  • 6
  • 25
  • 52

1 Answers1

1

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);
brandeded
  • 2,080
  • 6
  • 25
  • 52
King King
  • 61,710
  • 16
  • 105
  • 130
  • Thanks. I am attempting to pull the intersecting area of other `hwnd` not my form(s), so I don't think that method will work (?). – brandeded Oct 22 '13 at 20:59
  • 1
    @mbrownnyc of course, it won't but we have the static method `Screen.FromHandle`, you can use it instead. – King King Oct 22 '13 at 21:01