1.使用WIN32API,该方法模拟了一个左键拖动当前窗口标题栏的消息,仅对使用鼠标左键拖动窗口有效。由于调用了ReleaseCapture()函数,窗体原本的鼠标事件都无法得到响应。
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事件中实时设置窗体位置,该方法对左右键都有效,切不影响对其他鼠标事件的响应。
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);
}
}