C# 检测已单击窗体上的哪个Usercontrol

C# 检测已单击窗体上的哪个Usercontrol,c#,user-controls,C#,User Controls,我的情况如何? 我用的是C。我有一个表单,其中包含一个usercontrol的多个实例。usercontrol有三个按钮。添加、关闭并选择 我想要实现什么? 我想在单击用户控件实例的关闭按钮时获取该实例的标记 任何帮助都将不胜感激 谢谢在用户控件中,向按钮添加事件处理程序。在Eventhandler中触发一个事件,在表单中向其中添加一个Eventhandler 编辑:类似这样的 编辑2:更改它以满足海报要求 public delegate void UControlButtonCloseClic

我的情况如何? 我用的是C。我有一个表单,其中包含一个usercontrol的多个实例。usercontrol有三个按钮。添加、关闭并选择

我想要实现什么? 我想在单击用户控件实例的关闭按钮时获取该实例的标记

任何帮助都将不胜感激


谢谢

在用户控件中,向按钮添加事件处理程序。在Eventhandler中触发一个事件,在表单中向其中添加一个Eventhandler

编辑:类似这样的 编辑2:更改它以满足海报要求

public delegate void UControlButtonCloseClickedHandler(UControl sender, EventArgs e);
public partial class UControl : UserControl
{
    public event UControlButtonCloseClickedHandler UControlButtonCloseClicked;

    public UControl()
    {
        InitializeComponent();

        btnAdd.Click += ButtonAdd_Click;
        btnSelect.Click += ButtonSelect_Click;
        btnClose.Click += ButtonClose_Click;
    }


    private void ButtonClose_Click(object sender, EventArgs e)
    {
        UControlButtonCloseClicked(this, new EventArgs());
    }
}

在您的表单中,只需添加一个处理程序,如
uControl.UControlButtonCloseClicked+=Hanlder

为什么不将每个按钮链接到同一事件,然后获取控件的名称,以确定它是否为关闭按钮(因为每个控件必须具有唯一的名称,除非您将控件动态添加到表单中,但即使是这样,您也应该指定一个名称)。编辑:获取名称实际上是指比较触发事件的控件是否与要执行关闭操作、打开操作等的控件相同:)


我不太清楚否决票的原因,因为它用一个样本和解释回答了这个问题。行为不端。。。
        public Form1()
    {
        InitializeComponent();
        btnCloseButton.Click += new EventHandler(OnUserControlClick);
        btnOtherRandomButton.Click += new EventHandler(OnUserControlClick);
        btnOtherRandomButton1.Click += new EventHandler(OnUserControlClick);
    }

    private static void OnUserControlClick(object sender, EventArgs e)
    {
        if (sender as UserControl == btnCloseButton)
        {
            this.Close();
        }
    }