将图片从其他表单分配到图片框

时间:2019-10-04 14:48:04

标签: vb.net picturebox

我有一个程序,在主窗体(MainForm)上有16个空白的图片框。

当用户单击一个框时,将打开第二个窗体(form2),该窗体包含17个图片框,每个图片框都有一个特定的图像。我希望特定图像进入在主窗体上单击的图片框。

当我点击17个图片框之一时,我在form2上使用了此代码

With Mainform.picturebox1
    .image = My.Resources._apicture01
     End With

但是,当我在主窗体上单击picturebox2时,在form2中选择的图片将分配给Mainform.picturebox1而不是picturebox2

我需要一种使代码找出在主窗体上的16个图片框中被单击的代码,然后将其添加到该图片框中的方法。

2 个答案:

答案 0 :(得分:0)

这是我要解决的问题:

  • 在Form2上创建一个属性,用于存储单击的图像
  • 在您的PictureBox单击Form2上的事件中,将属性设置为相应的PictureBox的图像,将窗体的DialogResult设置为“确定”,然后关闭窗体。
  • 在Form1上的PictureBox单击事件中,在窗体上调用ShowDialog,检查DialogResult是否正常,如果是,则将相应PictureBox的图像设置为第一步中声明的属性

在Form2中,您将添加所有PictureBox控件并在设计器中设置它们的图像。您的Form2代码如下所示:

Public Class Form2
  Public Property SelectedImage As Image

  Private Sub Form2_PictureBoxClicked(ByVal sender As Object, ByVal e As EventArgs) Handles PictureBox1.Click, PictureBox2.Click, PictureBox3.Click, PictureBox4.Click, PictureBox5.Click, PictureBox6.Click, PictureBox7.Click, PictureBox8.Click, PictureBox9.Click, PictureBox10.Click, PictureBox11.Click, PictureBox12.Click, PictureBox13.Click, PictureBox14.Click, PictureBox15.Click, PictureBox16.Click, PictureBox16.Click
    Dim clickedButton As Button = DirectCast(sender, PictureBox)
    With Me
      .SelectedImage = clickedButton.Image
      .DialogResult = DialogResult.Ok
      .Close()
    End With
  End Sub
End Class

然后在Form1中,将所有PictureBox控件添加到设计器中,Form1的代码如下所示:

Public Class Form1
  Private Sub Form1_PictureBoxClicked(ByVal sender As Object, ByVal e As EventArgs) Handles PictureBox1.Click, PictureBox2.Click, PictureBox3.Click, PictureBox4.Click, PictureBox5.Click, PictureBox6.Click, PictureBox7.Click, PictureBox8.Click, PictureBox9.Click, PictureBox10.Click, PictureBox11.Click, PictureBox12.Click, PictureBox13.Click, PictureBox14.Click, PictureBox15.Click, PictureBox16.Click
    Dim clickedButton As Button = DirectCast(sender, PictureBox)
    Using frm2 As Form2 = New Form2()
      If frm2.ShowDialog() = DialogResult.Ok Then
        clickedButton.Image = frm2.SelectedImage
      End If
    End Using
  End Sub
End Class

答案 1 :(得分:0)

我认为有两种方法。第一个假设您的form2仅用于选择照片,然后关闭,返回到“主要”表单。

在这种情况下,将公共图像属性添加到form2中,如下所示:

Private _selectedImage As Image
Public ReadOnly Property SelectedImage As Image
    Get
        Return _selectedImage
    End Get
End Property

然后在form2中,选择图像时,将_selectedImage设置为图像并使用以下命令关闭表单:

Me.DialogResult = DialogResult.OK

回到主窗体,为所有图片框的Click事件设置事件处理程序,例如:

AddHandler PictureBox1.Click, AddressOf PictureBox_Click
AddHandler PictureBox2.Click, AddressOf PictureBox_Click

,依此类推。点击事件处理程序应如下所示:

    Private Sub PictureBox_Click(sender As Object, e As EventArgs) 
      Dim PB As PictureBox = DirectCast(sender, PictureBox)
      Using F As New Form2()
        If F.ShowDialog = DialogResult.OK Then
            PB.Image = F.SelectedImage
        End If
      End Using
    End Sub

另一种方法是将图片框作为属性或参数传递给Form2,然后在Form2中将图像设置为该图片框,但我更喜欢选项1。