在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);
}
}