C#实现无边框拖到的两种方式

3 篇文章 0 订阅
2 篇文章 0 订阅

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了)。

缺点是,还得多加一些方法优化窗口移动效果。

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值