2012-07-30 144 views
1

我創建了一個循環文件​​夾並檢索每個圖像文件並在窗體上繪製一個picturebox的函數。 下面是函數:C#:獲取picturebox的文件路徑onclick

private void Create_Controls(string Img_path) 
    { 
     PictureBox p = new PictureBox(); 
     p.Size = new Size(138, 100); 
     p.Location = new Point(6, 6); 
     p.BackgroundImage = Image.FromFile(Img_path); 
     p.BackgroundImageLayout = ImageLayout.Stretch; 

     this.Controls.Add(p); 
    } 

所以我需要做的是:每當我在的形式,與圖像文件路徑的消息彈出任何PictureBox的點擊。

所以我認爲有關添加自定義事件:

p.Click += delegate { Pop_Up(); }; 

private void Pop_Up() 
    { 
     /* POP UP MESSAGE WITH Picturebox image file path*/ 
    } 

回答

4

只要做到以下幾點:

p.Click += new EventHandler(Pop_Up); 

... 

private void Pop_Up(object sender, EventArgs e) 
{ 
    var pb = sender as PictureBox; 
    if(pb != null) 
    MessageBox.Show(pb.ImageLocation); 
} 
+0

非常感謝,它幫助和工作。 – 2012-07-30 13:00:51

4

您需要使用該圖片框的屬性ImageLocation。該屬性獲取或設置要在PictureBox中顯示的圖像的路徑或URL。

1

您可以使用Tag屬性。

這樣的事情。

private void Create_Controls(string Img_path) 
{ 
    PictureBox p = new PictureBox(); 
    p.Size = new Size(138, 100); 
    p.Location = new Point(6, 6); 
    p.Tag = Img_path; 
    p.BackgroundImage = Image.FromFile(Img_path); 
    p.BackgroundImageLayout = ImageLayout.Stretch; 

    this.Controls.Add(p); 
} 

private void Pop_Up() 
{ 
    MessageBox.Show(p.Tag); 
} 

有關這方面的Go here

1

然後沿着什麼HatSoft說,改變你的Pop_up()方法,如:

private void Pop_Up(object sender, EventArgs e) 
    { 
     MessageBox.Show(((PictureBox)sender).ImageLocation); 
    } 

但也許,如果它是更優雅和檢查了一下確實是一個PictureBox