Home > Back-end >  Is there any general WindowsFormApp event listener?
Is there any general WindowsFormApp event listener?

Time:10-26

Is there any WindowsFormApp listener method that automatically monitors events from child elements? Clicking a button, opening a list, etc... without each one having its own method?

I'm trying to automate the event process bound to WindowsFormApp components. Example: There are 10 buttons and I want a single method to monitor the actions of those 10 buttons or any other contained element. I already tried the manual method said at Set the handler. I want to know if there is an automated way, that is, some method of WindowsFormApp that is able to identify these events.

I await reply..

Thank you!

CodePudding user response:

All very well!

I applied the following snippet to define the Click event of any element that has this action.

foreach (Control grandChild in this.Controls) grandChild.Click  = new System.EventHandler(this.Handle_events);

    private void Handle_events(object sender, EventArgs e)
        {
          Console.WriteLine(sender);

        }

CodePudding user response:

You may add Event Handlers dynamically to ensure that they are the same for all children.

Panel p = new();
Button a = new();
Button b = new();

p.Controls.Add(a);
p.Controls.Add(b);
foreach (Button button in p.Controls) button.Click  = Button_Click;

void Button_Click(object sender, EventArgs e)
{
   ((Button)sender).Text = "I was clicked";
}
  • Related