我遇到了一个问题,我必须检查具有位置 X 和 Y 以及宽度和高度的表单是否包含在从具有矩形 X、Y、宽度和高度的窗口中检索的矩形对象中。我在使用 winforms 时有以下代码。如果你在窗口的边框之外,这段代码应该返回 false!
if (!(this.Location.Y > rect.Y && this.Location.Y < ((rect.Y + rect.Height) - this.Height)) || !(this.Location.X > rect.X && rect.X < ((this.Location.X + rect.Width) - this.Width)))
我使用以下代码段获取矩形:
IntPtr hWnd = FindWindow(null, this.windowTitle);
RECT rect;
GetWindowRect(hWnd, out rect);
其中这是窗体,rect是从窗口创建的矩形对象。
怎么样:
if(!(this.Location.Y > rect.Y && this.Location.X > rect.X &&
this.Location.X < rect.X + rect.Width && this.Location.Y < rect.Y + rect.Height)){
//...
}
System.Drawing.Rectangle
类有很好的方法。 您可以使用rectangle1.Contains(rectangle2)
你的问题基本上只是一个坐标参照的问题。
不太复杂的想法是使用相同的函数使用 Form.Handle 属性获取两个矩形,该属性基本上是一个句柄,就像 FindWindow 返回的句柄一样:
IntPtr hWnd = FindWindow(null, this.windowTitle);
RECT rect1;
GetWindowRect(hWnd, out rect);
RECT rect2;
GetWindowRect(form.handle, out rect);
return rect2.Y >= rect1.Y && rect2.Y + rect2.Height <= rect1.Y + rect1.Height && rect2.X >= rect1.X && rect2.X + rect2.Width <= rect1.X + rect1.Width
出于某种原因,你想写一些半优化的代码 -
if (!
(this.Location.Y > rect.Y &&
this.Location.Y < ((rect.Y + rect.Height) - this.Height))
||
!
(this.Location.X > rect.X &&
rect.X < ((this.Location.X + rect.Width) - this.Width)))
不幸的是,大多数人无法推理否定和或是相同的陈述。您还决定,与其比较每个角,不如将顶部/左侧与其他矩形的相对角和第一个矩形的大小的奇怪组合进行比较,以使条件更加复杂。
对于所有子条件,用单否定和 AND 重写相同的条件可能是正确且更具可读性的(请注意,以前有奇怪的非对称条件,现在都非常相似):
if (!
(this.Location.Y > rect.Y &&
this.Location.Y + this.Height < rect.Y + rect.Height &&
this.Location.X > rect.X &&
this.Location.X + this.Width < rect.X + rect.Width)
) {}
你到底问什么,但如果我理解正确,这应该可以工作
Rectangle rect = new Rectangle(-100,-100, 10, 10);
if (this.ClientRectangle.IntersectsWith(rect))
{
// do stuff
}