WinForm繪製選框矩形時,從右下向左上拖拽會產生Width/Height為負數的Rectangle,導致IntersectsWith判斷失效。
Rectangle結構體允許負寬高,但IntersectsWith基於標準矩形(左上角為原點,寬高為正)計算交集。負數參數破壞了幾何假設。
// 矩形標準化:確保Width、Height為正數
if (MouseRect.Width < 0) {
MouseRect.X = MouseRect.X + MouseRect.Width; // 左邊界右移
MouseRect.Width = -MouseRect.Width; // 寬度取絕對值
}
if (MouseRect.Height < 0) {
MouseRect.Y = MouseRect.Y + MouseRect.Height; // 上邊界下移
MouseRect.Height = -MouseRect.Height; // 高度取絕對值
}
// 正常交集判斷
foreach (Control ct in tab.Controls) {
if (MouseRect.IntersectsWith(ct.Bounds)) {
addListRect(ct);
}
}
負寬矩形: 標準化後: X=100, W=-50 → X=50, W=50 │◄── -50 ──►│ │◄── 50 ──►│ 左邊界實際在50 左邊界修正為50
public static Rectangle Normalize(this Rectangle rect) {
if (rect.Width < 0) {
rect.X += rect.Width;
rect.Width = -rect.Width;
}
if (rect.Height < 0) {
rect.Y += rect.Height;
rect.Height = -rect.Height;
}
return rect;
}
// 使用
MouseRect = MouseRect.Normalize();