To pass a new instance of a form to a procedure
-
Open a project, create a new form and add a command button named
Button1to it. -
Copy the following code into the
Button1_clickevent:
Protected Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
Dim newForm As New Form1()
newForm.Show()
CenterForm(newForm)
End SubSub CenterForm(ByVal TheForm As Form)
' Centers the form on the screen.
Dim RecForm As rectangle = Screen.GetBounds(TheForm)
TheForm.Left = CInt((RecForm.Width - TheForm.Width) / 2)
TheForm.Top = CInt((RecForm.Height - TheForm.Height) / 2)
End Sub
You can also pass an object as an argument by reference and then, inside the procedure, set the argument to a new object.
To pass an object reference to a procedure on another form
-
Open a project and create a form named
Form1. -
Add a second form named
Form2. -
Place a picture box control on each form.
-
Name the picture box on form1
PictureBox1. -
Name the picture box on form2
PictureBox2. -
Assign a picture to
PictureBox2by clicking the Image property in the Properties window. Any small images will work; you can find .bmp and .jpg files in your Windows directory. -
Add the following code to
Form2:
Public Sub GetPicture(ByVal x As PictureBox)
Dim objX As PictureBox
' Assign the passed-in picture box to an object variable.
objX = x
' Assign the value of the Picture property to the Form1 picture box.
objX.Image = PictureBox2.Image
End Sub
-
Add the following code to the Form1_Click event on
form1:
Protected Sub Form1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)
Dim newForm2 As New Form2()
newForm2.GetPicture(PictureBox1)
End SubRun the application and click
Form1. The picture fromForm2appears in the picture box onForm1.The Form1_Click event procedure calls the
GetPictureprocedure inForm2, and passes the empty picture box to it. TheGetPictureprocedure inForm2assigns the Image property of the picture box onForm2to the empty picture box onForm1, and the image fromForm2is displayed onForm1.

Join the conversation! Your thoughts help the community grow.