0

您好,我有这个为表单创建标签的循环:

  private Label newLabel = new Label();
    private int txtBoxStartPosition = 300;
    private int txtBoxStartPositionV = 25;

    private void button1_Click(object sender, EventArgs e)
    {
        int txt = Int32.Parse(textBox1.Text);
        for (int i = 0; i < txt; i++)
        {
            newLabel = new Label();
            newLabel.Location = new System.Drawing.Point(txtBoxStartPosition, txtBoxStartPositionV);
            newLabel.Size = new System.Drawing.Size(25, 25);
            newLabel.Text = i.ToString();
            newLabel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            newLabel.ForeColor = Color.Red;
            newLabel.Font = new Font(newLabel.Font.FontFamily.Name, 10);
            newLabel.Font = new Font(newLabel.Font, FontStyle.Bold);
            newLabel.TextAlign = System.Drawing.ContentAlignment.MiddleRight;  

            this.Controls.Add(newLabel);
            txtBoxStartPosition -= 35;


        }

而且我在 MouseMove 和 MouseDown 上有一些事件,使控件可以用鼠标抓取和放下。

        private Point MouseDownLocation;

    private void MyControl_MouseDown(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            MouseDownLocation = e.Location;
        }
    }

    private void MyControl_MouseMove(object sender, MouseEventArgs e)
    {
        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            label1.Left = e.X + label1.Left - MouseDownLocation.X;
            label1.Top = e.Y + label1.Top - MouseDownLocation.Y;
        }
    }

我的问题是:有什么方法可以将这些事件分配给新创建的标签?

在此先感谢您的时间。

4

2 回答 2

3

尝试这个:

newLabel.MouseMove += MyControl_MouseMove;
newLabel.MouseDown += MyControl_MouseDown;

周杰伦

于 2013-09-30T21:33:00.820 回答
3

您需要连接和取消连接您的事件。闲置的处理程序是内存泄漏的来源。

List<Label> myLabels = new List<Label>(txt);

for (int i = 0; i < txt; i++)
{
    newLabel = new Label();
    newLabel.MouseMove += MyControl_MouseMove;
    newLabel.MouseDown += MyControl_MouseDown;
    myLabels.Add(newLabel);
.......

// Later in Dispose
foreach (var lbl in myLabels)
{
     lbl -= MyControl_MouseMove;
     lbl -= MyControl_MouseDown;
}
myLabels.Clear();
于 2013-09-30T21:46:07.440 回答