动态添加的事件处理程序

本文关键字:程序 事件处理 添加 动态 | 更新日期: 2023-09-27 18:04:00

好的,我没有解释清楚,我如何在所有表单上搜索控件名称?

  ` void No1(Form a, int x, int y)
    {
        No2(a, x, y);
    }
    void No2(Form a, int x, int y)
    {
        Button b1 = new Button();
        b1.Location = new Point(x, y);
        b1.Click += new EventHandler(b1_click);
        b1.Name = "OgO4sEVm6asqnw";
        a.Controls.Add(b1);
    }
    void b1_click(object sender, EventArgs e)
    {
        a.Controls.RemoveByKey("OgO4sEVm6asqnw");
        No1(a, x, y);   //I have no way to get a, x and y, 
                        //since I don't know on witch form b1 is
    }`

动态添加的事件处理程序

知道在哪个形式b1是通过转换sender

void b1_click(object sender, EventArgs e)
{
    if (sender is Button)
    {
        var b1 = (Button) sender;
        b1.Parent.Controls.RemoveByKey(b1.Name);
        No1(b1.TopLevelControl, b1.Location.X, b1.Location.Y);
    }                   
}

属性TopLevelControl给你的形式和Parent给你的ControlContainer(可以是形式,也可以是面板)