C# 无边框窗体 移动 两种方法

本文介绍了两种实现窗体拖动的方法。第一种利用Windows API,通过调用ReleaseCapture()和SendMessage()函数实现类似标准窗口的拖动效果,但可能影响其他鼠标事件响应。第二种方法结合MouseMove、MouseDown和MouseUp事件,提供更灵活的拖动控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网上和书上大致有两种方法,各有长短吧。 一种是使用Windows API:

//需添加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。有时候是不能忍的。
 
第二种方法则是结合三种窗体或控件的鼠标事件来完成

 

 private void panel1_MouseMove(object sender, MouseEventArgs e)
        {
            if (beginMove)
            {
                this.Left += MousePosition.X - currentXPosition;//根据鼠标x坐标确定窗体的左边坐标x 
                this.Top += MousePosition.Y - currentYPosition;//根据鼠标的y坐标窗体的顶部,即Y坐标 
                currentXPosition = MousePosition.X;
                currentYPosition = MousePosition.Y;
            } 

        }

        private void panel1_MouseDown(object sender, MouseEventArgs e)
        {
            
            if (e.Button == MouseButtons.Left)
            {
                beginMove = true;
                currentXPosition = MousePosition.X;//鼠标的x坐标为当前窗体左上角x坐标 
                currentYPosition = MousePosition.Y;//鼠标的y坐标为当前窗体左上角y坐标              } 
            }

        }

        private void panel1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                beginMove = false;
                currentXPosition = MousePosition.X;//鼠标的x坐标为当前窗体左上角x坐标 
                currentYPosition = MousePosition.Y;//鼠标的y坐标为当前窗体左上角y坐标              } 
            }
        }

beginMove,currentXPosition,currentYPosition 为全局定义变量;

转载于:https://www.cnblogs.com/cylamg/p/3447389.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值