C#如何将picturebox click事件组合到相应的函数?

时间:2019-03-06 08:25:58

标签: c# picturebox

C#如何将picturebox点击事件与相应的功能结合在一起?

private void pbx_process(int i) 
{ 
   PictureBox picture_box 
      = this.Controls.Find("pbx_image" + i, true).FirstOrDefault() 
        as PictureBox; 
   if (picture_box.Image != null) pbx_image.Image = picture_box.Image; 
   else pbx_image.Image = null; 
} 

private void pbx_image1_Click(object sender, EventArgs e) 
{ 
    pbx_process(1); 
}

private void pbx_image2_Click(object sender, EventArgs e) 
{ 
    pbx_process(2); 
}

private void pbx_image3_Click(object sender, EventArgs e) 
{ 
    pbx_process(3); 
}

我想使这些变得简单。请帮助。...

1 个答案:

答案 0 :(得分:0)

创建这样的函数

AddEvent()
{
pbx_image1.click+=pbx_image_Click;
pbx_image2.click+=pbx_image_Click;
pbx_image3.click+=pbx_image_Click;
}

然后

private void pbx_image_Click(object sender, EventArgs e) 
{ 

    pbx_process(sender as PictureBox); or you can do the process right here
}

然后

private void pbx_process(PictureBox pictureBox) 
{ 

   if (pictureBox.Image != null) pbx_image.Image = pictureBox.Image; 
   else pbx_image.Image = null; 
} 

请记住在表单加载后将事件添加到图片框中,然后调用AddEvent函数。