2013-05-09 32 views
0

我正在使用圖像查看器並遇到一個小問題。哪個pictureBox被選中onClick? C#

我使用對話框將圖像加載到程序中,然後將它們放入單獨的圖片框中。

我不知道如何爲每個圖片框執行onclick,因爲當它被點擊時,我希望該圖片顯示在更大的圖片框中。

public partial class Form1 : Form 
{ 
    List<Bitmap> images = new List<Bitmap>(); 
    public Form1() 
    { 

     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     int x = 0; 
     openFileDialog1.Filter = "Image Files(*.jpg; *.jpeg; *.bmp)|*.jpg; *.jpeg; *.bmp"; 
     openFileDialog1.Multiselect = true; 

     if (openFileDialog1.ShowDialog() == DialogResult.OK) 
     { 
      foreach(String fileName in openFileDialog1.FileNames) 
      { 
       images.Add(new Bitmap(fileName)); 
       PictureBox pb = new PictureBox(); 
       Image loadedImage = Image.FromFile(fileName); 
       pb.SizeMode = PictureBoxSizeMode.StretchImage; 
       pb.Width = flowLayoutPanel1.Width; 
       pb.Height = 200; 
       pb.Image = loadedImage; 
       pb.MouseClick += pb_MouseClick; 
       flowLayoutPanel1.Controls.Add(pb); 
       pb.Name = "" + x; 
       x++; 
      } 
     } 
    MessageBox.Show(String.Format("{0} images loaded",images.Count),"",MessageBoxButtons.OK); 
    } 

    private void Form1_Load(object sender, EventArgs e) 
    { 

    } 

    void pb_MouseClick(object sender, MouseEventArgs e) 
    { 
     // handle click event 
     if (e.Button == MouseButtons.Left) 
      MessageBox.Show("Image clicked"); 

     pbMain.Image = images[0]; 
     pbMain.SizeMode = PictureBoxSizeMode.StretchImage; 
    } 
} 

回答

3

如果在圖片框的Click處理程序,投senderPictureBox像這樣:

PictureBox pb = (PictureBox)sender; 

然後,你不需要知道具體是被點擊了其中一個。只需使用該參考來抓取圖像並將其放入較大的框中即可。