Domanda

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?

È stato utile?

Soluzione

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
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top