随心所欲移动Panel
C# Winform编程时,有时需要在程序执行时,使窗体中的panel控件可以随意的移动,这时可以采用下面这种方法:
主要包括以下两步:
@1:给panel(此处以 RealGLPanel为例说明)添加MouseDown和MouseMove事件处理函数,如此处对应为: RealGLPanel_MouseMove
和 RealGLPanel_MouseDown
@2:编写两个函数的实现代码(真的不长,不要怕)
具体的代码实现如下:
1 private void RealGLPanel_MouseDown(object sender, MouseEventArgs e) 2 { 3 oldRealGLPLPt.X = this.RealGLPanel.Location.X; 4 oldRealGLPLPt.Y = this.RealGLPanel.Location.Y; 5 6 RealGLPLPt.X = Cursor.Position.X; 7 RealGLPLPt.Y = Cursor.Position.Y; 8 this.RealGLPanel.BringToFront(); 9 } 10 11 private void RealGLPanel_MouseMove(object sender, MouseEventArgs e) 12 { 13 if (e.Button == MouseButtons.Left) 14 { 15 int tx, ty; 16 tx = Cursor.Position.X - RealGLPLPt.X; 17 ty = Cursor.Position.Y - RealGLPLPt.Y; 18 19 if (tx != 0 || ty != 0) 20 { 21 int tempx = oldRealGLPLPt.X + tx; 22 int tempy = oldRealGLPLPt.Y + ty; 23 24 //此处可以添加对tempx和tempy的限定的代码 25 26 this.RealGLPanel.Location = new System.Drawing.Point(tempx, tempy); 27 } 28 this.RealGLPanel.BringToFront(); 29 } 30 }