C# 无边框窗体移动,MouseDown后不触发MouseClick

.Net技术 码拜 9年前 (2015-09-01) 3478次浏览 0个评论

由于Winform的默认窗体样式太丑了,所以隐藏边框成为很多开发人员的选择,但是边框的作用主要是移动窗体的,没有边框就需要解决移动窗体和最大化,最小化问题了。最大化和最小化比较简单,这里主要介绍无边框移动窗体问题:一共有2种方式。

第一种 使用Windows API方式:拖动效果和正常窗口拖动效果差不多,但是ReleaseCapture()会使窗口的某些Mouse事件无法响应。例如MouseDown后不触发MouseClick事件

//需添加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 Control_MouseDown(object sender, MouseEventArgs e)
{
      if (e.Button == MouseButtons.Left)
     {
           ReleaseCapture(); //释放鼠标捕捉
           //发送左键点击的消息至该窗体(标题栏)
           SendMessage(Handle, 0xA1, 0x02, 0);
      }

 }

第二种方法是在3个Mouse事件中共同实现。如下:

bool beginMove = false;//初始化

      int currentXPosition;
        int currentYPosition;
        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
                if (e.Button == MouseButtons.Left)
               {
            beginMove = true;
            currentXPosition = MousePosition.X;//鼠标的x坐标为当前窗体左上角x坐标
            currentYPosition = MousePosition.Y;//鼠标的y坐标为当前窗体左上角y坐标
             }
        }
        private void Form1_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 Form1_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
                {
                    currentXPosition = 0; //设置初始状态
                    currentYPosition = 0;
                       beginMove = false;
              }
           }

这种方法在C#中不用调用API。缺点是,还得多加一些方法优化窗口移动效果。由于无边框情况下移动窗体功能和控件的MouseClick事件都需要使用到,所以使用了第二种方式。

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明C# 无边框窗体移动,MouseDown后不触发MouseClick
喜欢 (1)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!