C#實作無邊框拖到的兩種方式
a、一種是使用Windows API:
先建立一個項目示範一下
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLiAzNfRHLGZkRGZkRfJ3bs92YsYTMfVmepNHL6VFVPVTRE9kMNpHW4Z0MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL1QTO4IjMwEDM2AjMxgTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
選擇窗體的屬性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了)。
缺點是,還得多加一些方法優化視窗移動效果。