C#WinForm無邊框窗體移動方法、模仿鼠標單擊標題欄移動窗體位置

C#WinForm無邊框窗體移動方法、模仿鼠標單擊標題欄移動窗體位置

這裏介紹倆種辦法測試

方法一:直接經過修改窗體位置從而達到移動窗體的效果this

方法二:直接假裝發送單擊任務欄消息,讓應用程序誤覺得單擊任務欄從而移動窗體spa

新建窗體用於測試.net

方法一

1.定義一個位置信息Point用於存儲鼠標位置

1         private Point mPoint;

2.給窗體等控件增長MouseDown和MouseMove事件

 1         /// <summary>
 2         /// 鼠標按下
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void panel1_MouseDown(object sender, MouseEventArgs e)
 7         {
 8             mPoint = new Point(e.X, e.Y);
 9         }
10 
11         /// <summary>
12         /// 鼠標移動
13         /// </summary>
14         /// <param name="sender"></param>
15         /// <param name="e"></param>
16         private void panel1_MouseMove(object sender, MouseEventArgs e)
17         {
18             if (e.Button == MouseButtons.Left)
19             {
20                 this.Location = new Point(this.Location.X + e.X - mPoint.X, this.Location.Y + e.Y - mPoint.Y);
21             }
22         }

方法二:

1.引入下面代碼 前提須要引入命名空間using System.Runtime.InteropServices

1         [DllImport("user32.dll")]
2         public static extern bool ReleaseCapture();
3 
4         [DllImport("user32.dll")]
5         public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
6 
7         private const int VM_NCLBUTTONDOWN = 0XA1;//定義鼠標左鍵按下
8         private const int HTCAPTION = 2;

2.增長鼠標按下事件發送消息,讓系統誤覺得按下是標題欄

 1         /// <summary>
 2         /// 鼠標按下
 3         /// </summary>
 4         /// <param name="sender"></param>
 5         /// <param name="e"></param>
 6         private void panel1_MouseDown(object sender, MouseEventArgs e)
 7         {
 8             //爲當前應用程序釋放鼠標捕獲
 9             ReleaseCapture();
10             //發送消息 讓系統誤覺得在標題欄上按下鼠標
11             SendMessage((IntPtr)this.Handle, VM_NCLBUTTONDOWN, HTCAPTION, 0);
12         }

測試效果

 

動態圖演示

 

 源代碼工程文件下載

相關文章
相關標籤/搜索