在WinForm程式中,要移動沒有標題欄的視窗,基本的實現思路是監聽需要拖動視窗內的控制項的滑鼠事件,然後將滑鼠位置發送給視窗進行相應的位移就可以了。通過借用Windows API也可以很容易實現這一點,比如像下麵這樣。 public class Win32Api { public const int ...
在WinForm程式中,要移動沒有標題欄的視窗,基本的實現思路是監聽需要拖動視窗內的控制項的滑鼠事件,然後將滑鼠位置發送給視窗進行相應的位移就可以了。通過借用Windows API也可以很容易實現這一點,比如像下麵這樣。
public class Win32Api
{
public const int WM_SYSCOMMAND = 0x112;
public const int SC_DRAGMOVE = 0xF012;
[DllImport("user32.Dll", EntryPoint = "ReleaseCapture")]
public extern static void ReleaseCapture(); // 滑鼠捕獲
[DllImport("user32.Dll", EntryPoint = "SendMessage")]
public extern static void SendMessage(IntPtr hWnd, int wMsg, int wParam, int lParam); // 將消息發送給指定的視窗
}
private void pnlHeader_MouseDown(object sender, MouseEventArgs e)
{
Win32Api.ReleaseCapture();
Win32Api.SendMessage(this.Handle, Win32Api.WM_SYSCOMMAND, Win32Api.SC_DRAGMOVE, 0);
}
當然,你還可以向這樣向視窗發送消息,來實現拖動自定義標題欄移動視窗
public const int WM_NCLBUTTONDOWN = 0x00A1;
public const int HTCAPTION = 2;
private void pnlHeader_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
// 釋放控制項已捕獲的滑鼠
pnlHeader.Capture = false;
// 創建併發送WM_NCLBUTTONDOWN消息
Message msg =
Message.Create(this.Handle, Win32Api.WM_NCLBUTTONDOWN,
new IntPtr(Win32Api.HTCAPTION), IntPtr.Zero);
this.DefWndProc(ref msg);
}
}