如何覆盖按钮单击C#(Winforms)



让我从示例开始:我有一个Form,其中一个名为" btntest" 并添加了_click事件。

private void btnTest_Click(object sender, EventArgs e)
        {
            MessageBox.Show("button click");
        }

现在,我想使用Control类动态生成此button的另一个_click事件,因此覆盖了现有的event_hendler,因此我的表格看起来像这样:

 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        Control[] controls = Controls.Find("btnTest", true); //find control by name
        controls[0].Click += Form1_Click; //generate button click
    }
    private void Form1_Click(object sender, EventArgs e)
    {
        MessageBox.Show("control click"); //want to be displayed
    }
    private void btnTest_Click(object sender, EventArgs e)
    {       
        MessageBox.Show("button click");  //don't want to be displayed
    }
}

因此,我的目标是启用 Form1_Click iongore btnTest_Click,并在代码中动态地做到这一点。做了一些研究,但无法得到答案。

我为什么要这样做?

我的主要目标是使用 Enter 关键字而不是 TAB> TAB 浏览控件,因此,当我偶然发现按钮时,我只想在不触发原始事件的情况下向前迈进。<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<</p>

请注意,btnTest_Click事件是在Form1_Click事件之前触发的,并且不良解决方案是直接在btnTest_Click中执行某些操作,因为我有有限的控件,我想使用 Enter> Enter 进行导航,并且HAT可更改,可更改,可更改,因此,我要忽略的按钮将在controls数组中。

任何建议都是有帮助的,谢谢您的时间。

您如何看待这种方法

Control control = Controls.Find("btnTest", true).FirstOrDefault(); //find control by name
if(control != null)
{
  btnTest.Click -= btnTest_Click; //Remove Default Event Handler.
  control.Click += Form1_Click; //generate button click
}

尝试以下:

controls[0].Click += Form1_Click;
controls[0].Click -= btnTest_Click;

经过一些挣扎和研究,我设法找到了解决方案。我的逻辑是在controls[0].Click += Form1_Click;之前删除所有事件Hendlers,这将是覆盖原始事件的方法。尝试过这样的某个

 controls[0].Click += null;
 controls[0].Click += Form1_Click;

但是它行不通,所以我根据这个答案找到了解决方案,我的论坛看起来像这样:

        public Form1()
        {
            InitializeComponent();
            InitializeComponent();
            Control[] controls = Controls.Find("btnTest", true); //find control by name
            Button btn = controls[0] as Button;    //safe cast as Button     
            RemoveClickEvent(btn); 
            controls[0].Click += Form1_Click; //generate button click
        }
        private void Form1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("control click"); 
        }
        private void btnTest_Click(object sender, EventArgs e)
        {
            MessageBox.Show("button click"); 
        }
        //remove all event hendlers for button 
        private void RemoveClickEvent(Button b)
        {
            FieldInfo f1 = typeof(Control).GetField("EventClick",
                BindingFlags.Static | BindingFlags.NonPublic);
            object obj = f1.GetValue(b);
            PropertyInfo pi = b.GetType().GetProperty("Events",
                BindingFlags.NonPublic | BindingFlags.Instance);
            EventHandlerList list = (EventHandlerList)pi.GetValue(b, null);
            list.RemoveHandler(obj, list[obj]);
        }

最新更新