C# 移动无边框窗体

来源:互联网 发布:汽车网络宣传方案 编辑:程序博客网 时间:2024/06/08 01:10
private Point mouseOffset;
private bool isMouseDown = false;

private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
    int xOffset;
    int yOffset;

    if (e.Button == MouseButtons.Left) 
    {
        xOffset = -e.X /*- SystemInformation.FrameBorderSize.Width*/;
        yOffset = -e.Y /*- SystemInformation.CaptionHeight - SystemInformation.FrameBorderSize.Height*/;
        mouseOffset = new Point(xOffset, yOffset);
        isMouseDown = true;
    }
}
private void Form1_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
    if (isMouseDown) 
    {
        Point mousePos = Control.MousePosition;
        mousePos.Offset(mouseOffset.X, mouseOffset.Y);
        Location = mousePos;
    }
}

private void Form1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
    if (e.Button == MouseButtons.Left) 
    {
        isMouseDown = false;
    }
}
另一种
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);
   public const int WM_SYSCOMMAND = 0x0112;
   public const int SC_MOVE = 0xF010;
   public const int HTCAPTION = 0x0002;

private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
ReleaseCapture();
SendMessage(this.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
}