在我的程序中,我需要在Windows窗体中复制一个Label,并且我通过以下方式实现它:
public partial class Resizer : Form
{
public Resizer()
{
InitializeComponent();
}
private Control toChange = new Control();
private Control selected = new Control();
private bool readyToMove = false;
private Point offset;
private void pictureBox4_Click(object sender, EventArgs e)
{
selected.Location = ((Control)sender).Location;
selected.Size = ((Control)sender).Size;
}
private void backClick(object sender, EventArgs e)
{
selected = null;
}
private void Resizer_Load(object sender, EventArgs e)
{
pictureBox4.MouseDown += new MouseEventHandler(this.dynamicMouseDown);
pictureBox4.MouseMove += new MouseEventHandler(this.dynamicMouseMove);
pictureBox4.MouseUp += new MouseEventHandler(this.dynamicMouseUp);
}
private void dynamicMouseDown(object sender, MouseEventArgs e)
{
toChange = (Control)sender;
selected.Location = ((Control)sender).Location;
selected.Size = ((Control)sender).Size;
readyToMove = true;
offset = new Point(PointToClient(MousePosition).X - selected.Location.X,
PointToClient(MousePosition).Y - selected.Location.Y);
}
private void dynamicMouseMove(object sender, MouseEventArgs e)
{
if (readyToMove)
{
selected.Location = new Point(PointToClient(MousePosition).X-offset.X,
PointToClient(MousePosition).Y- offset.Y);
this.Update();
}
}
private void dynamicMouseUp(object sender, MouseEventArgs e)
{
toChange.Location = selected.Location;
readyToMove = false;
}
private void button1_Click(object sender, EventArgs e)
{
PictureBox pBox = (PictureBox)CloneObject(this.pictureBox4);
this.Controls.Add(pBox);
//pBox.MouseDown += new MouseEventHandler(this.dynamicMouseDown);
//pBox.MouseMove += new MouseEventhandler(this.dynamicMouseMove);
//pBox.MouseUp += new MouseEventHandler(this.dynamicMouseUp);
//these eventhandlers did not help...
}
private object cloneObject(object o)
{
Type t = o.GetType();
System.Reflection.PropertyInfo[] properties = t.GetProperties();
Object p = t.InvokeMember("",
System.Reflection.BindingFlags.CreateInstance,
null,
o,
null);
foreach (PropertyInfo pi in properties)
{
if (pi.CanWrite)
pi.SetValue(p, pi.GetValue(o, null), null);
}
return p;
}
}
老问题:
问题是,只要我点击labelOrigin
,窗口就会冻结,我无法再关闭表单了。为什么这样,我该如何解决?
现在:
正如您所看到的,这实现了拖放操作,通过按下按钮,您可以复制表单。
问题是,新的pBox不可移动并导致图形错误。
在添加button1和pictureBox4 之后,此代码应该在一个简单的表单上工作