原文:http://blog.csdn.net/lcawen88/article/details/7942801
在实现Label控件拖动,这里介绍两种有效地方法:
其一,通过调用api,通过消息来实现拖动(需要调用命名空间using System.Runtime.InteropServices;):
[DllImport("User32.DLL")]
public static extern int SendMessage(IntPtr hWnd, uint Msg, int wParam, int lParam);
[DllImport("User32.DLL")]
public static extern bool ReleaseCapture();
public const uint WM_SYSCOMMAND = 0x0112;
public const int SC_MOVE = 61456;
public const int HTCAPTION = 2;
private void label1_MouseDown(object sender, MouseEventArgs e)
{
ReleaseCapture();
SendMessage(((Label)sender).Handle, WM_SYSCOMMAND, SC_MOVE | HTCAPTION, 0);
}
其二,只是用MouseDown和MouseMove两个事件实现拖动:
private Point m_lastPoint;
private Point m_lastMPoint;
private void label1_MouseDown(object sender, MouseEventArgs e)
{
m_lastMPoint = Control.MousePosition;
m_lastPoint = (sender as Label).Location;
}
private void label1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
label1.Location = new Point(m_lastPoint.X + Control.MousePosition.X - m_lastMPoint.X, m_lastPoint.Y + Control.MousePosition.Y - m_lastMPoint.Y);
}
}