Multiple Control Click Events handled by one event

感情迁移 提交于 2019-12-23 02:31:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!