鼠标拖动区域边框,选中边框内的控件

 

   网上实现该功能的代码很少,为了大家都学习就把它发出来
public partial class Form11 : Form { bool MouseIsDown = false; Rectangle MouseRect = Rectangle.Empty; Rectangle RgionRect = Rectangle.Empty; public Form11() { InitializeComponent(); this.MouseDown += new MouseEventHandler(frmMain_MouseDown); this.MouseMove += new MouseEventHandler(frmMain_MouseMove); this.MouseUp += new MouseEventHandler(frmMain_MouseUp); } void frmMain_MouseUp(object sender, MouseEventArgs e) { this.Capture = false; Cursor.Clip = Rectangle.Empty; MouseIsDown = false; DrawRectangle(); //画完后的矩形区域保存到RgionRect 矩形内,然后在RgionRect 矩形内判断控件是否在该矩形内,设置选中状态 RgionRect =MouseRect ; //判断选中状态 CheckSelect(panel1); MouseRect = Rectangle.Empty; } void CheckSelect(Panel gb) { foreach (Label item in gb.Controls) { //得到控件的矩形区域 Rectangle controlSize = new Rectangle(item.Location, item.Size); //得到画出的矩形位置。位置不一定在左上角要转换后在判断 Point rangPoint = SaveRect.Location; if (SaveRect.Width < 0 && SaveRect.Height > 0) { SaveRect.Location = new Point(rangPoint.X - Math.Abs(SaveRect.Width), rangPoint.Y); SaveRect.Width = Math.Abs(SaveRect.Width); } else if (SaveRect.Width >= 0 && SaveRect.Height < 0) { SaveRect.Location = new Point(rangPoint.X, rangPoint.Y - Math.Abs(SaveRect.Height)); SaveRect.Height = Math.Abs(SaveRect.Height); } else if (SaveRect.Width < 0 && SaveRect.Height < 0) { SaveRect.Location = new Point(rangPoint.X - Math.Abs(SaveRect.Width), rangPoint.Y - Math.Abs(SaveRect.Height)); SaveRect.Height = Math.Abs(SaveRect.Height); SaveRect.Width = Math.Abs(SaveRect.Width); } //如果画出的矩形和控件的矩形相交叉 if (SaveRect.IntersectsWith(controlSize)) { item.Text = "选中"; } } } void frmMain_MouseMove(object sender, MouseEventArgs e) { if (MouseIsDown) ResizeToRectangle(e.Location); } void frmMain_MouseDown(object sender, MouseEventArgs e) { MouseIsDown = true; DrawStart(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.White, FrameStyle.Dashed); } private void DrawStart(Point StartPoint) { this.Capture = true; Cursor.Clip = this.RectangleToScreen(new Rectangle(0, 0, ClientSize.Width, ClientSize.Height)); MouseRect = new Rectangle(StartPoint.X, StartPoint.Y, 0, 0); } }
posted @ 2012-06-15 16:15  行走的娃娃  阅读(1215)  评论(1编辑  收藏  举报