C#中无边框窗体拖动

时间:2021-08-27 21:11:24

C#中无边框窗体拖动

         //定义一个bool变量标识是否拖动窗体
private bool isMove = false;
//记录鼠标的位置
private Point point;

定义的变量

         /// <summary>
/// 窗体的鼠标按下事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
isMove = true;
//记录鼠标的位置
point = e.Location;
}

窗体的鼠标按下事件

         /// <summary>
/// 窗体的鼠标移动事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
//是否移动窗体
if (isMove)
{
//记录鼠标移动后的值
Point p = e.Location;
//计算鼠标按下和移动后的距离
int x = p.X - point.X;
int y = p.Y - point.Y;
//窗体的位置
this.Location = new Point(this.Location.X + x, this.Location.Y + y);
}
}

鼠标移动事件

         /// <summary>
/// 鼠标弹起事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
//不允许在移动窗体
isMove = false;
}

鼠标弹起事件

Demo下载地址:

无边框拖动窗体.zip