I have a winforms app in vs2010 and a panel whose click event I would like to fire programatically. How do I do this? Button has a PerformClick but I cannot find the same in Panel.
Asked
Active
Viewed 3,390 times
2
-
2Your panel's Click event is going to be attached to a function, yes? Then, call this function and don't bother on performing a click... it will have the same result. – Gusman Feb 29 '16 at 10:16
-
Just call `Panel_Click(null,null)` – Pikoh Feb 29 '16 at 10:16
-
Check this SO questions http://stackoverflow.com/questions/12184614/trigger-controls-event-programmatically, http://stackoverflow.com/questions/372974/winforms-how-to-programatically-fire-an-event-handler and also https://msdn.microsoft.com/en-us/library/wkzf914z(v=vs.90).aspx – Cizaphil Feb 29 '16 at 10:25
-
@Gusman this would make for my preferred (and upvoted) solution, rather than creating ones own Button class and overriding the click handler, as suggested in one of the linked answers. May I suggest making it into an answer? – CompuChip Feb 29 '16 at 10:30
-
2I would recommend *not* passing `null` to the event handler. That's going to cause perfectly reasonable code inside of the event handler that relies on those parameters being non-null to fail. At the very least, pick a reasonable sending object and pass `EventArgs.Empty` as the second parameter. – Cody Gray - on strike Feb 29 '16 at 10:33
-
@CodyGray you are completely right. It was just a "quick and dirty" suggestion, as OP is not telling what the code inside the Click event is doing :) – Pikoh Feb 29 '16 at 10:35
1 Answers
2
Your panel's Click event is going to be attached to an event handler, right?
Then just call that event handler from the button's click event handler:
public void Panel1_Click(object sender, EventArgs e)
{
//Do whatever you need to do
}
public void Button1_Click(object sender, EventArgs e)
{
//Do anything you need to do first
Panel1_Click(Panel1, EventArgs.Empty);
}
The effect will be the same as clicking on the panel.

Gusman
- 14,905
- 2
- 34
- 50
-
-
-
How do you call a function that you don't have access to in the current scope? – DCOPTimDowd Feb 13 '19 at 16:59
-
If you don't have access to it, how did you attached it to the button's event? – Gusman Feb 14 '19 at 11:18
-
I'm asking why it doesn't matter where a function is when it comes to calling it, as you claimed. I'm curious as I am unaware of a way to do that. – DCOPTimDowd Feb 14 '19 at 17:13
-
Sorry but I don't understand you, I'm sick and I'm not sure if I'm missing something in your question. First of all, if you have attached the function to the event, in some point you had access to it, so you can store a reference using a delegate or a Func/Action. Also, even in the case you didn't stored the reference, the function is attached to the event through a delegate, so you can use reflection to get the attached delegates to the event and use that delegate to invoke the function. – Gusman Feb 15 '19 at 00:29