我在基于C#.net的Windows应用程序中工作...在应用程序中我动态创建控件并将鼠标事件添加到那个..但是在移动子控件时它移出了父控件..我在Code下面试过..但是它没有用......那我们怎么做呢?
private Point start = Point.Empty;
private bool _mapPackageIsMoving;
Control SelectedControl = null;
private void button3_Click_1(object sender, EventArgs e)
{
Label lbl = new Label();
lbl.Name = "id1";
lbl.Text = "move";
lbl.MouseDown += new MouseEventHandler(label1_MouseDown);
lbl.MouseMove += new MouseEventHandler(label1_MouseMove);
lbl.MouseUp += new MouseEventHandler(label1_MouseUp);
this.panel2.Controls.Add(lbl);
SelectedControl = lbl;
}
void label1_MouseUp(object sender, MouseEventArgs e)
{
_mapPackageIsMoving = false;
}
void label1_MouseMove(object sender, MouseEventArgs e)
{
Label lControl = sender as Label;
if (lControl != null)
{
if (_mapPackageIsMoving)
{
int nx = Math.Min(Math.Max(lControl.Left + (e.X - start.X), 0), lControl.Parent.Width - SelectedControl.Width);
int ny = Math.Min(Math.Max(lControl.Top + (e.Y - start.Y), 0), lControl.Parent.Height - SelectedControl.Height);
lControl.Location = new Point(nx, ny);
}
}
}
void label1_MouseDown(object sender, MouseEventArgs e)
{
start = e.Location;
_mapPackageIsMoving = true;
}
答案 0 :(得分:1)
您需要剪切光标,即阻止光标移动到父母标签的面板之外。以下更改应该有所帮助。
void label1_MouseDown(object sender, MouseEventArgs e)
{
start = e.Location;
_mapPackageIsMoving = true;
Cursor.Clip = panel2.RectangleToScreen(panel2.ClientRectangle);
}
void label1_MouseUp(object sender, MouseEventArgs e)
{
_mapPackageIsMoving = false;
Cursor.Clip = null;
}
CodeProject上的Drag and Drop on a Windows Form是一个方便的参考(代码在VB.NET中)。