繁体   English   中英

C#:获取picturebox onclick的文件路径

[英]C# : get the file path of 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);
    }

因此,我需要做的是:每当我单击表单上的任何图片框时,都会弹出带有图像文件路径的消息。

所以我想添加一个自定义事件:

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

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

您需要使用PictureBox的ImageLocation属性。 该属性获取或设置要在PictureBox中显示的图像的路径或URL。

只需执行以下操作:

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);
}

您可以为此使用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);
}

有关更多信息,请转到此处

然后连同HatSoft所说的一样,更改您的Pop_up()方法,例如:

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

但是也许更优雅一些,并检查它是否确实是PictureBox等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM