在网上抄的,写得很好。
http://www.cnblogs.com/yoker/articles/1221932.html
让咱们也玩窗体拖动,支持用TextBox,Label,ListBox...
创建一个类文件:MyDragForm.cs
代码如下:
[C#_Code]
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Elephant.FormUtils
{
class MyDragForm
{
private static bool isMouseDown = false;
private static Point mouseOffset;
private static Form _form;
public MyDragForm()
{
}
///
/// 设定你要启用的控件
///
/// 使用的控件对象,支持lable,textbox等
public static void bindControl(Control control_)
{
//使用的控件
if (control_ == null)
{
return;
}
_form = control_.FindForm();
//加载消息
control_.MouseMove += new MouseEventHandler(control_MouseMove);
control_.MouseDown += new MouseEventHandler(control_MouseDown);
control_.MouseUp += new MouseEventHandler(control_MouseUp);
}
private static void control_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
Control control_ = sender as Control;
//计算新点位置
int offsetX = -e.X;
int offsetY = -e.Y;
if (!(control_ is System.Windows.Forms.Form))
{
offsetX = offsetX - control_.Left;
offsetY = offsetY - control_.Top;
}
if (_form.FormBorderStyle != FormBorderStyle.None)
{
offsetX = offsetX - SystemInformation.FrameBorderSize.Width;
offsetY = offsetY - SystemInformation.FrameBorderSize.Height - SystemInformation.CaptionHeight;
}
//重绘得新的位置
mouseOffset = new Point(offsetX, offsetY);
//鼠标点下,启示将要移动
isMouseDown = true;
}
}
private static void control_MouseMove(object sender, MouseEventArgs e)
{
//移动标志
if (isMouseDown)
{
//赋予新的位置
Point mouse = Control.MousePosition;
mouse.Offset(mouseOffset.X, mouseOffset.Y);
_form.Location = mouse;
}
}
private static void control_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
//标志,不再移动
isMouseDown = false;
}
}
}
}
[/C#_Code]
调用代码:
MyDragForm.bindControl(this.lbl_systemname);
在页面拖动lbl_systemname这个标签,页面便一起拖动。