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

时间:2022-11-06 13:32:37

转载自:http://blog.sina.com.cn/s/blog_6b7c38030100xx17.html

网上和书上大致有两种方法,各有长短吧。
一种是使用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。有时候是不能忍的。

第二种方法是在某几个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了)。缺点是,还得多加一些方法优化窗口移动效果。