1.使用WIN32API,該方法模擬了一個左鍵拖動當(dāng)前窗口標(biāo)題欄的消息,僅對使用鼠標(biāo)左鍵拖動窗口有效。由于調(diào)用了ReleaseCapture()函數(shù),窗體原本的鼠標(biāo)事件都無法得到響應(yīng)。
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[System.Runtime.InteropServices.DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
private void Form1_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
ReleaseCapture();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
2.在OnMouseMove事件中實時設(shè)置窗體位置,該方法對左右鍵都有效,切不影響對其他鼠標(biāo)事件的響應(yīng)。
public partial class DragForm : Form
{
// Offset from upper left of form where mouse grabbed
private Size? _mouseGrabOffset;
public DragForm()
{
InitializeComponent();
}
protected override void OnMouseDown(MouseEventArgs e)
{
if( e.Button == System.Windows.Forms.MouseButtons.Right )
_mouseGrabOffset = new Size(e.Location);
base.OnMouseDown(e);
}
protected override void OnMouseUp(MouseEventArgs e)
{
_mouseGrabOffset = null;
base.OnMouseUp(e);
}
protected override void OnMouseMove(MouseEventArgs e)
{
if (_mouseGrabOffset.HasValue)
{
this.Location = Cursor.Position - _mouseGrabOffset.Value;
}
base.OnMouseMove(e);
}
}