Passing control's MouseClick event to its container

痞子三分冷 提交于 2019-12-11 07:54:27

问题


I'll try to be concise but comrehensible. I have a dynamic 2-dimensional array of PictureBox elements, and they're all added to the same form via:

this.Controls.Add(PictureBoxArray[i,j]);

Now I've designed an algorithm that would determine which of these PBs are clicked, but I've placed it in the ParentForm_MouseClick method. And now I've reached a paradox. The algorithm I've created returns the proper output, but the ParentForm_MouseClick method is called only when I click on the empty space in the Form, not when I click on PictureBoxes. So my question is - how can I invoke ParentForm_MouseClick method when users click anywhere in the form i.e. can I somehow override PictureBoxes' MouseClick events so that ParentForm_MouseClick is invoked instead?

EDIT: This just occured to me, could I create a custom PictureBoxClass Class that extends the .NET one and just override the MouseClick() event to invoke a method I've previously written?


回答1:


It seems like you're over-complicating things. If you're going to need to call the code within an event handler from different places, it's a good idea to abstract that out to a different method. You can attach the same event handler to the PictureBoxes which then call that method.

for(int i = 0; i < PictureBoxArray.GetLength(0); i++) 
{
    for(int j = 0; j < PictureBoxArray.GetLength(1); j++)
    {
        //attach handler
        PictureBoxArray[i,j].Click += pictureBox_Click;
    }
}


void pictureBox_Click(object sender, EventArgs e)
{
   MyMethod();      
}

void parentForm_Click(object sender, EventArgs e)
{
   MyMethod();       
}

private void MyMethod()
{
   //method to be called
}


来源:https://stackoverflow.com/questions/17907436/passing-controls-mouseclick-event-to-its-container

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