winform拖动鼠标显示矩形选择区域

因为最近一个项目通过winform做一个仓库的2D俯视仿真图,其中客户要求能对存储箱做“柔性分区”。所以想通过鼠标拖动矩形框选择控件的方式来确定用户想要的分区。在网上搜寻了一下winform的鼠标拖动矩形框的代码,对他的代码(http://heisetoufa.iteye.com/blog/380977)整理了一下。兹只以博客为笔记本来加强记忆。

View Code
#region mouseRectanger
void panel1_MouseUp(object sender, MouseEventArgs e)
{
//this.Capture = false;
this.panel1.Capture = false;
Cursor.Clip
= Rectangle.Empty;
MouseIsDown
= false;
}

private void panel1_MouseDown(object sender, MouseEventArgs e)
{
DrawRectangle();
MouseIsDown
= true;
DrawStart(e.Location);
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (MouseIsDown)
ResizeToRectangle(e.Location);
}
private void ResizeToRectangle(Point p)
{
DrawRectangle();
MouseRect.Width
= p.X - MouseRect.Left;
MouseRect.Height
= p.Y - MouseRect.Top;
DrawRectangle();
}
private void DrawRectangle()
{
Rectangle rect
= this.RectangleToScreen(MouseRect);
ControlPaint.DrawReversibleFrame(rect, Color.Green, FrameStyle.Dashed);
}
private void DrawStart(Point StartPoint)
{
//this.Capture = true;
this.panel1.Capture = true;
//这是设置鼠标筐选时鼠标的移动区域 和控件对鼠标的捕获
//Cursor.Clip = this.RectangleToScreen(new Rectangle(0, 0, ClientSize.Width, ClientSize.Height));
Cursor.Clip = this.RectangleToScreen(this.panel1.ClientRectangle);
MouseRect
= new Rectangle(StartPoint.X, StartPoint.Y, 0, 0);
}

#endregion

绿线为鼠标拖出的矩形选择框,中间为PictureBox控件,表示储物箱

以下是获取选择区内的控件

View Code
Control interSectCtl = null;
foreach (Control ctl in panel1.Controls)
{
if (ctl.Bounds.IntersectsWith(MouseRect))
{
interSectCtl
= ctl;
if (interSectCtl.GetType() == typeof(System.Windows.Forms.PictureBox))
{
PictureBox picBox
= (PictureBox)ctl;
}
continue;
}
}
posted @ 2011-08-16 15:12  jeffreyQ  阅读(3525)  评论(0编辑  收藏  举报
跟小D每日学口语
跟小D每日学口语