添加点击事件打开个别图片框图片

Add click event to open individual picture box image

我正在将图片框中的图像添加到流式布局面板。我正在尝试添加一个点击事件,以便当在 flowlayout 面板中单击图像时,它将打开原始图像。我的照片是.jpg。这是我到目前为止得到的,但似乎没有用。

For Each pic As FileInfo In New DirectoryInfo("picturepath").GetFiles("file.jpg")
    Dim picture As New PictureBox
    picture .Height = 113
    picture .Width = 145
    picture .BorderStyle = BorderStyle.Fixed3D
    picture .SizeMode = PictureBoxSizeMode.Zoom
    picture .Image = Image.FromFile(fi.FullName)

    AddHandler picture.MouseClick, AddressOf pictureBox_MouseClick
    flowlayoutpanel.Controls.Add(picture)
Next

Public Sub pictureBox_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
     ====>>> Not sure what goes here to get the correct path of that image since there could be more than one images.
End Sub

您需要使用 "sender" 参数来获取对被单击的 PictureBox 的引用:

Public Sub pictureBox_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
    Dim pb As PictureBox = DirectCast(sender, PictureBox)
    ' ... now do something with "pb" (and/or "pb.Image") ...
End Sub

仅引用 PictureBox(如我上面的示例),您将只引用图像本身。如果您想要文件的完整路径,那么您必须以某种方式将该信息与 PictureBox 一起存储;使用标签 属性 是一种简单的方法:

Dim picture As New PictureBox
...
picture.Image = Image.FromFile(fi.FullName)
picture.Tag = fi.Fullname

现在您可以在单击事件中检索该文件名并对其执行一些操作:

Public Sub pictureBox_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
    Dim pb As PictureBox = DirectCast(sender, PictureBox)

    ' ... now do something with "pb" (and/or "pb.Image") ...
    Dim fileName As String = pb.Tag.ToString()
    Process.Start(fileName)
End Sub