第一種,利用windows的消息機制來實現:
首先﹐.定義鼠標左鍵按下時的Message標識﹔其次﹐在Form1_MouseDown方法﹐讓操作系統誤以為是按下標題欄。
1.定義鼠標左鍵按下時的Message標識
private const int WM_NCLBUTTONDOWN = 0XA1; //.定義鼠標左鍵按下
private const int HTCAPTION = 2;
2.讓操作系統誤以為是按下標題欄
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
//為當前的應用程序釋放鼠標鋪獲
ReleaseCapture();
//發送消息﹐讓系統誤以為在標題欄上按下鼠標
SendMessage((int)this.Handle,WM_NCLBUTTONDOWN,HTCAPTION,0);
}
3.申明程序中所Windows的API函數
[DllImport("user32.dll",EntryPoint="SendMessageA")]
private static extern int SendMessage(int hwnd,int wMsg,int wParam,int lParam);
[DllImport("user32.dll")]
private static extern int ReleaseCapture();
第二種,通過自定鼠標左鍵按下時產生的事件:
* 首先將窗體的邊框樣式修改為None,讓窗體沒有標題欄
* 實現這個效果使用了三個事件:鼠標按下、鼠標彈起、鼠標移動
* 鼠標按下時更改變量isMouseDown標記窗體可以隨鼠標的移動而移動
* 鼠標移動時根據鼠標的移動量更改窗體的location屬性,實現窗體移動
* 鼠標彈起時更改變量isMouseDown標記窗體不可以隨鼠標的移動而移動
*/
private bool isMouseDown = false;
private Point FormLocation; //form的location
private Point mouseOffset; //鼠標的按下位置
private void Form1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isMouseDown = true;
FormLocation = this.Location;
mouseOffset = Control.MousePosition;
}
}
private void Form1_MouseUp(object sender, MouseEventArgs e)
{
isMouseDown = false;
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
int _x = 0;
int _y = 0;
if (isMouseDown)
{
Point pt = Control.MousePosition;
_x = mouseOffset.X - pt.X;
_y = mouseOffset.Y - pt.Y;
this.Location = new Point(FormLocation.X - _x, FormLocation.Y - _y);
}
}