Fire an event simultaneously for multiple dynamic controls in c# winform

时间:2015-12-14 17:53:48

标签: c# winforms c#-5.0 eventhandler

I have N number of dynamically added PictureBoxes in FlowLayoutPanel. When I create them I attach event handlers to them. For example:

for(int i=0;i<x;i++) {    
    var pe= new PictureBox();
    pe.MouseUp+=mouseup;
    pe.MouseDown+=mouseDown;
    pe.MouseMove+=mouseMove;
    pe.Paint+=paint;
}

My goal is to fire those events for all picture boxes whenever I work with any one of them. For example, if I move one picturebox (1st/2nd/3rd/.../n ) all others will move automatically, if I zoom any box, others will zoom automatically. How can I fire events simultaneously for all pictureboxes when I work with anyone.

If I try for example:

void mouseWheel(object sender, MouseEventArgs e) {
    var control=(PictureBox)sender;
    var parent=control.parent;
    var pictureBoxes=parent.ofType<PictureBox>();

    foreach(pb in pictureBoxes) {
                //do something
    }
}

It only works for the picture box I am working with.

2 个答案:

答案 0 :(得分:1)

您需要调用方法而不是引发事件。

创建一些方法并在方法上放置逻辑,然后在事件处理程序中,首先提取所需的信息,然后使用参数调用合适的方法。

例如:

void pictureBox_MouseWheel(object sender, MouseEventArgs e)
{
    //Some parameter that you extract from eventArgs or somewhere else
    int zoomFactor = e.Delta;

    //Call the method on your picture boxes
    foreach (var p in pictureBoxes)
    {
        Zoom(p, zoomFactor);
    }
}

//The method that contains logic of zoom on a picture box
public void Zoom(PictureBox p, int zoomFactor)
{
    //It is just an example, not a real logic
    p.SizeMode = PictureBoxSizeMode.Zoom;
    p.Width += (zoomFactor * 10);
    p.Height += (zoomFactor * 10);
}

我认为您在创建它们时已在List<PictureBox>中添加了所有图片框。

此外,如果您已将图片框添加到控件的Controls集合中,例如theControl,那么您可以稍后以这种方式找到它们:

var pictureBoxes = theControl.Controls.OfType<PictureBox>().ToList();

答案 1 :(得分:0)

It looks like you already have a list of picture boxes. So, try modifying your functions (for example your Zoom function) to work for all picture boxes in the list, rather than just the one picture box.

In other words, don't try to call the event handler for each picture box, make each event handler call a function, which modifies all picture boxes.