求助:c#实现界面上拖动label.
小弟的代码是这么写的,但是实现不了功能,请各位大侠帮助一下。。。 如果在label的事件 MouseDown MouseUp 中直接写控制坐标的代码,只能实现移动,但是看不出拖动的效果。。。
public partial class Form1 : Form
{
private int oldX = -1;
private int oldY = -1;
public Form1()
{
InitializeComponent();
}
private void Form1_DragEnter(object sender, DragEventArgs e)
{
//
e.Effect = DragDropEffects.Move;
}
private void label1_MouseDown(object sender, MouseEventArgs e)
{
this.DoDragDrop(label1, DragDropEffects.Move);
oldX = e.X;
oldY = e.Y;
}
private void label1_MouseUp(object sender, MouseEventArgs e)
{
int nX, nY;
nX = e.X;
nY = e.Y;
label1.Left += nX - oldX;
label1.Top += nY - oldY;
oldX = -1;
oldY = -1;
}
}
------解决方案--------------------
不使用Drag的事件,直接使用MouseDown,MouseMove就可以了:
C# code
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);
}
}