Sunday, July 26, 2009

With Command Explained

Introduction
As mentioned above this tutorial focuses on the With command in Visual Basic 6.0, you can use it to control object on your forms and to set the properties like you can with the click of a mouse. I can hear you ask "Why use this when you can set properties with mouse clicks?". Well the answer is, in the programming world most people use this method and you can then easily change the property without going through any wizards or anything.

Requirements
For this tutorial you will need a Windows based operating system with a copy of Visual Basic 6.0 installed. Nothing else...

The With Command
I feel this command is sometimes underrated and most definantly underused in programs I have seen. People tend not to use this command as the Properties Window in Visual Basic allows you to do it much quicker without typing lines of code. In fact all you are doing is writing the code without typing (if that makes sense).

The syntax for this is really simple...

With objectname
'perform code
End With
Simply enough you replace the object name section with the name of your object e.g. dlgSplash. From here you can use the . (dot) to bring up the syntax suggest list of attributes to set. In our example we will load a splash dialog and then load the main program form.

So say we startup with a sub-routine called main. Using our with command we will show the dlgSplash form and refresh it.

Sub main()
'start with
With dlgSplash
'show form
.Show

'refresh form
.Refresh

End With
End Sub
Simple enough eh? All this does is shorten the dlgSplash.Show to what you see above in the example. Our final code example will have the code above and then load the new form for the main program and remove the splash dialog.
Sub main() 'start with With dlgSplash 'show form .Show 'refresh form .Refresh
'show program form frmMain.Show
'unload splash Unload dlgSplash
End WithEnd Sub
As you may have guessed by now we can shorten the frmMain.Show to this...
With frmMain .ShowEnd With
However if you have a property call in this in an if function for example you have to referenceit properly even though the With may already be where your object is.

No comments:

Post a Comment