克隆标签导致C#
在我的程序中,我需要在Windows窗体中复制标签,并通过以下方式实现:克隆标签导致C#,c#,winforms,controls,C#,Winforms,Controls,在我的程序中,我需要在Windows窗体中复制标签,并通过以下方式实现: public partial class Resizer : Form { public Resizer() { InitializeComponent(); } private Control toChange = new Control(); private Control selected = new Control(); private bool
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;
}
}
老问题:
问题是,只要我点击标签,窗口就会冻结,我无法再关闭表单。这是为什么?我该如何修复它?
现在:
如您所见,这实现了一个拖放,通过按下按钮,您可以复制表单。。
问题是,新的pBox不能移动,并且会导致图形错误。。
在添加按钮1和图片bx4之后,此代码应该可以在一个简单的表单上工作。为什么要使它变得如此复杂?如果你只需要克隆一个标签,那么你只需要复制x、y、文本,如果你设置了一些自定义内容(宽度、高度、字体),因为以后我想用其他控件来做。。是的,可能有不同的设置已从标准更改。。因此,我希望避免在所有情况下重写新函数。您是否尝试将代码放入try-catch块?否则,即使没有错误,foreach也必须处于无限循环中。是的,在该代码周围添加一个try catch
。它可能不会“冻结”,它可能会抛出一个安静的异常,永远不会返回。不,我进行了调试,它似乎可以毫无问题地执行所有代码。。。