為了界面的好看,有時候需要將窗體FormBorderStyle屬性設為None,這樣就可以根據自己的喜歡來設計界面。但這樣窗體無法進行移動的。而且默認的窗體(FormBorderStyle=Sizable)只有點擊窗體邊框才能移動,點擊內容界面也是無法移動。根據網友們的介紹和總結,有兩種比較簡單的實現方法。
方法一:通過記錄窗體的位置,然后利用MouseDown、MouseUp、MouseMove這三個事件實現窗體的移動。
1 bool isMouseDown = false; 2 Point currentFormLocation = new Point(); //當前窗體位置 3 Point currentMouseOffset = new Point(); //當前鼠標的按下位置 4 private void Form1_MouseDown(object sender, MouseEventArgs e) 5 { 6 if (e.Button == MouseButtons.Left) 7 { 8 isMouseDown = true; 9 currentFormLocation = this.Location; 10 currentMouseOffset = Control.MousePosition; 11 } 12 } 13 14 private void Form1_MouseUp(object sender, MouseEventArgs e) 15 { 16 isMouseDown = false; 17 } 18 19 private void Form1_MouseMove(object sender, MouseEventArgs e) 20 { 21 int rangeX = 0, rangeY = 0; //計算當前鼠標光標的位移,讓窗體進行相同大小的位移 22 if (isMouseDown) 23 { 24 Point pt = Control.MousePosition; 25 rangeX = currentMouseOffset.X - pt.X; 26 rangeY = currentMouseOffset.Y - pt.Y; 27 this.Location = new Point(currentFormLocation.X - rangeX, currentFormLocation.Y - rangeY); 28 } 29 }
第二種方法:利用windows的消息機制來實現(轉自:http://www.cnblogs.com/techmango/archive/2012/03/31/2427523.html)
//首先﹐.定義鼠標左鍵按下時的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();
