C#实现无边框拖到的两种方式
a、一种是使用Windows API:
先建立一个项目演示一下
选择窗体的属性FormBorderStyle设置为 None
打开窗体代码
//需添加using System.Runtime.InteropServices;
选择窗体的鼠标按下事件
并加入下列代码:
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
//......
private void Form1_MouseDown(object sender, MouseEventArgs e)
{//窗体移动
if (e.Button == MouseButtons.Left)
{
ReleaseCapture(); //释放鼠标捕捉
//发送左键点击的消息至该窗体(标题栏)
SendMessage(Handle, 0xA1, 0x02, 0);
}
}
然后生成一下项目即可实现窗体移动;
这个方法,使用的话拖动效果和正常窗口拖动效果差不多,但是一句ReleaseCapture()就使窗口的某些Mouse事件无法响应。比如MouseClick。有时候是不能忍的。
b、第二种方法是在窗体几个Mouse事件中共同实现;
如下图:
具体代码实现如下:
#region C#无边框移动窗体第二种方式
bool beginMove = false;//初始化
int currentXPosition;
int currentYPosition;
#endregion
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
#region C#无边框移动窗体第二种方式
if (e.Button == MouseButtons.Left)
{
beginMove = true;
currentXPosition = MousePosition.X;//鼠标的x坐标为当前窗体左上角x坐标
currentYPosition = MousePosition.Y;//鼠标的y坐标为当前窗体左上角y坐标
}
#endregion
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
#region C#无边框移动窗体第二种方式
if (beginMove)
{
this.Left += MousePosition.X - currentXPosition;//根据鼠标x坐标确定窗体的左边坐标x
this.Top += MousePosition.Y - currentYPosition;//根据鼠标的y坐标窗体的顶部,即Y坐标
currentXPosition = MousePosition.X;
currentYPosition = MousePosition.Y;
}
#endregion
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
#region C#无边框移动窗体第二种方式
if (e.Button == MouseButtons.Left)
{
currentXPosition = 0; //设置初始状态
currentYPosition = 0;
beginMove = false;
}
#endregion
}
这种方法在C#中比较正规(不用调用API了)。
缺点是,还得多加一些方法优化窗口移动效果。