PictureBox 的图像不会出现在新窗体中,该窗体在停用时应关闭

The Image of a PictureBox doesn't appear in a new Form, which should close when deactivated

PictureEdit 或 PictureBox 的图像未以新形式显示 (Form2)。
此外,当单击父窗体 (form1) 中的不同控件时,这个新窗体应该会自动关闭。

使用我的代码,当我双击 Form1 中的图像时,只出现第三个图像。

请问有什么解决方法可以不用按照Form1的图片数量新建3个form吗?

为了记录,我使用 Visual Studio 2010

Public Class Form1
   Private Sub PictureEdit1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles PictureEdit1.DoubleClick
        Dim yourForm As New Form2()
        yourForm.ShowDialog()
    End Sub

    Private Sub PictureEdit2_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles PictureEdit2.DoubleClick
        Dim yourForm As New Form2()
        yourForm.ShowDialog()
    End Sub
    Private Sub PictureEdit3_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles PictureEdit3.DoubleClick
        Dim yourForm As New Form2()
        yourForm.ShowDialog()
    End Sub
End Class

Public Class Form2
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim Form_One As Form1 = CType(Application.OpenForms("form1"), Form1)
        Me.PictureEdit1.Image = Form_One.PictureEdit1.Image
        Me.PictureEdit1.Image = Form_One.PictureEdit2.Image
        Me.PictureEdit1.Image = Form_One.PictureEdit3.Image
    End Sub
End Class

需要的小改动:

  • 向接受图像作为参数的 Form2 添加一个构造函数。
  • 覆盖 OnDeactivate,以在您单击窗体外部 时关闭窗体。
  • 使用 Show(Me) 而不是 ShowDialog():这将使调用 Form 成为 Form2 的所有者,因此它位于其所有者之上,但它不是模态 Window,当您在其外部单击时,它不会被停用。

Public Class Form1
   ' [...]
   Private Sub PictureEdit1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles PictureEdit1.DoubleClick
        Dim f2 As New Form2(PictureEdit1.Image)
        f2.Show(Me)
    End Sub
    ' [...]
End Class

Public Class Form2
    Public Sub New()
        Me.New(Nothing)
    End Sub
    Public Sub New(img As Image)
        InitializeComponent()
        PictureEdit1.Image = img
    End Sub

    Protected Overrides Sub OnDeactivate(e As EventArgs)
        MyBase.OnDeactivate(e)
        BeginInvoke(New Action(Sub() Close()))
    End Sub
End Class 

完成 Jimi 建议的更改后,您还可以使用一个子来处理所有三个 PictureEdit 控件,方法是在“处理”关键字后列出多个 control/event:

Private Sub PictureEditAll_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles PictureEdit1.DoubleClick, PictureEdit2.DoubleClick, PictureEdit3.DoubleClick
    Dim picEdit As PictureEdit = DirectCast(sender, PictureEdit)
    Dim f2 As New Form2(picEdit.Image)
    f2.Show(Me)
End Sub