问题
I am creating a basic winform application that has many pictureboxes with click events. The click events need to use the name of the picturebox that was clicked in order to execute the rest of the code. I do not want to create unique click events for all of the pictureboxes. I was hoping there would be a simple way to get this information, like using the "sender" parameter or the event arguments.
回答1:
You add one click event handler for all of the PictureBoxes:
pic1.Click += PictureBoxClick;
pic2.Click += PictureBoxClick;
Then cast the sender to a PictureBox to get which one was clicked, a rough example:
private void PictureBoxClick(object sender, EventArgs e)
{
var picBoxName = ((PictureBox)sender).Name;
}
Dont forget to unhook the event subscriptions in the form unload event:
pic1.Click -= PictureBoxClick;
pic2.Click -= PictureBoxClick;
来源:https://stackoverflow.com/questions/38710655/multiple-control-click-events-handled-by-one-event