如何从MDI Child保存图像

时间:2019-05-14 12:21:25

标签: vb.net

我想从MDI Child中保存图像,但出现此错误: enter image description here

这是代码

Private Sub mnuFileSep_Click(sender As Object, e As EventArgs) Handles mnuFileSep.Click
    Dim saveFile As SaveFileDialog = New SaveFileDialog
    saveFile.Title = "Save Files"
    saveFile.InitialDirectory = "C:\"
    saveFile.Filter = "Jpg File|*.jpg"

    If saveFile.ShowDialog() = DialogResult.OK Then
        'An error appears from the line below
        Form2.PictureBox1.Image.Save(saveFile.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

最可能的错误源是使用Form2。这可能会尝试访问Form2的“默认实例”,而您可能已经用“ new”关键字显示了另一个实例。

获取对Form2实际实例的引用的一种方法:

Private Sub mnuFileSep_Click(sender As Object, e As EventArgs) Handles mnuFileSep.Click
    Dim f2 As Form2 = Me.MdiChildren.OfType(Of Form2).FirstOrDefault
    If Not IsNothing(f2) Then
        Dim saveFile As New SaveFileDialog
        saveFile.Title = "Save Files"
        saveFile.InitialDirectory = "C:\"
        saveFile.Filter = "Jpg File|*.jpg"
        If saveFile.ShowDialog() = DialogResult.OK Then
            f2.PictureBox1.Image.Save(saveFile.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
        End If
    End If
End Sub

如果您打开了多个Form2实例,则可以检查活动MdiChild是否为Form2类型,并改用它:

Private Sub mnuFileSep_Click(sender As Object, e As EventArgs) Handles mnuFileSep.Click
    If Not IsNothing(Me.ActiveMdiChild) AndAlso TypeOf(Me.ActiveMdiChild) Is Form2 Then
        Dim f2 As Form2 = DirectCast(Me.ActiveMdiChild, Form2)
        Dim saveFile As New SaveFileDialog
        saveFile.Title = "Save Files"
        saveFile.InitialDirectory = "C:\"
        saveFile.Filter = "Jpg File|*.jpg"
        If saveFile.ShowDialog() = DialogResult.OK Then
            f2.PictureBox1.Image.Save(saveFile.FileName, System.Drawing.Imaging.ImageFormat.Jpeg)
        End If
    End If
End Sub