Basic Graphical User Interfaces

Level:
Level1

This VB6 tutorial will cover basic Graphical User Interface methods in Visual Basic. This is not a complicated topic, but it is something crucial if you are going to develop a good looking application.

Overview

If you've read some other beginner visual basic tutorials on this site, you're probably saying to yourself, "I thought this was supposed to be Visual Basic!" Indeed, Visual Basic is very much so an interface-oriented language, far moreso than other languages, and designing even complex graphical user interfaces (or GUIs) is quite simple.

In contrast to tradional, command-line interfaces, almost all user interfaces in Visual Basic are constructed using the WIMP, or "windows, icon, menu, pointer," GUI style. This means that Visual Basic programs interact with users almost exclusively using graphical elements, such as windows, buttons, toolbars, etc., with very few console-based applications (in fact, creating a console-based VB application is quite difficult, requiring advanced API techniques, which will be covered much later). While in previous lessons, we've made use of Debug.Print, which is not a WIMP element, it's important to note that the debugging, or intermediate, window is only visible in design mode, and not during typical program execution.

In this tutorial, we'll introduce and expand upon three basic methods of creating WIMP interfaces in Visual Basic: using the MsgBox function (which you've seen before), the InputBox function, and forms and controls.

MsgBox revisited

Up until now, we've blindly used this magical MsgBox function to display text without really understanding what it was, how it worked, or what could be done with it. Now that we have a bit more understanding of functions, subroutines, and control structures, let's take a somewhat closer look at it.

MsgBox is a actually a function, like many of the functions we've used and created before, provided by the standard VB runtime. Its function declaration is the following:

Public Function MsgBox( _
   ByVal prompt As String, _
   Optional ByVal buttons As Integer = vbOKOnly, _
   Optional ByVal title As String = Nothing _
   Optional ByVal helpfile As String = Nothing _
   Optional ByVal context As Integer = Nothing _
) As Integer

Having read Functions and Subroutines in VB6, you should now be able to recognize a few useful attributes of the MsgBox function. For one, MsgBox has a return type--Integer, which implies that we can not only display data in a MsgBox, but also get information back. The information we are able to retrieve from calling the MsgBox function is a numerical expression equating to a constant value that describes which button on the MsgBox was clicked. Legal return values for the MsgBox function are: vbOK, vbCancel, vbAbort, vbRetry, vbIgnore, vbYes, and vbNo.

Furthermore, we can specify which buttons and styles we want displayed on our message boxes using the "buttons" argument. If, for instance, we want to display a msgBox with the buttons "Abort," "Retry," and "Ignore," we can use the construct: MsgBox "Test", vbAbortRetryIgnore. If we further want to display this message box with a "Question" icon, we can use this construct: MsgBox "Test", vbAbortRetryIgnore + vbQuestion. There are many possible values for the button argument, and you can find a full list in the MSDN library.

With the title argument, we can also change the text we want to display in the caption of the message box by passing any legal String. The "helpfile" and "context" arguments will be explained later on in the course when we cover contextual help in VB6.

MsgBox examples

Now let's took a look at a simple example that makes use of MsgBox.

Public Sub Main()
   If MsgBox("Click a button.", vbOKCancel, "MsgBox Test") = vbOK Then
      MsgBox "You clicked OK!", vbOKOnly, "MsgBox Test"
   Else
      MsgBox "You clicked Cancel!", vbOKOnly, "MsgBox Test"
   End If
End Sub

And voila! We have a program that's capable of responding to user input! Now what if we to give the user three different options? We could do this:

Public Sub Main()
   If MsgBox("Click a button.", vbYesNoCancel, "MsgBox Test") = vbYes Then
      MsgBox "You clicked Yes!", vbOKOnly, "MsgBox Test"
   ElseIf MsgBox("Click a button.", vbYesNoCancel, "MsgBox Test") = vbNo Then
      MsgBox "You clicked No!", vbOKOnly, "MsgBox Test"
   Else
      MsgBox "You clicked Cancel!", vbOKOnly, "MsgBox Test"
   End If
End Sub

However, you may notice one major probelm with this code: it displays two message boxes instead of just one, which is what we expected. This is because each time you call MsgBox, a new message box is created. To respond to three different return types for one MsgBox, it's best to store the value in a variable and then perform tests on that variable. For example:

Public Sub Main()
   Dim ret As Integer
   
   ret = MsgBox("Click a button.", vbYesNoCancel, "MsgBox Test")
   If ret = vbYes Then
      MsgBox "You clicked Yes!", vbOKOnly, "MsgBox Test"
   ElseIf ret = vbNo Then
      MsgBox "You clicked No!", vbOKOnly, "MsgBox Test"
   Else
      MsgBox "You clicked Cancel!", vbOKOnly, "MsgBox Test"
   End If
End Sub

InputBox

Now let's take a quick look at a function similar to MsgBox that allows the user to provide a much, much wider array of valid inputs, namely the InputBox function. This function is provided by the standard VB6 runtime, and its declaration is as follows:

Public Function InputBox( _
   prompt As String, _
   Optional title As String = Empty, _
   Optional default As String = "", _
   Optional xpos As Single = Empty, _
   Optional ypos As Single = Empty, _
   Optional helpfile As String = Empty, _
   Optional context As Integer = 0 _
) As String

This function displays an InputBox, or a single dialog requesting a single line of ASCII input from the user, with the given prompt, title, default text (specified by default), and other argument values (which we won't get into in depth) and returns the String that the user provided the dialog. Let's take a look at a simple example:

Public Sub Main()
   Dim YourName As String
   YourName = InputBox("Please enter your name.", "InputBox demo")
   If Len(YourName) > 0 Then
      MsgBox "Your name is " + YourName
   Else
      MsgBox "You hit cancel or entered an empty string."
   End If
End Sub

This simple little program prompts the user for his or her name and then displays it in a MsgBox. If the user selected cancel the string returned will be an empty string (""). This very simple function now allows your program to behave in an infinite number of ways, as the InputBox dialog can except an infinite number of various inputs.

Forms and controls

In Introduction to VB6, you gained some basic knowledge of forms and controls. In this section, we'll attempt to expand upon that knowledge by discussing basic control-based GUI design, looking at some common controls, and introducing the properties of controls.

Forms

In Visual Basic, the Form is the primary component of every GUI application. A form is a unique kind of control, known as a top-level container, a control that can contain within it any number of controls but that cannot itself be contained by other containers. Forms can come in many shapes and sizes (we'll learn about modifying the appearance of forms a bit later), but typically they are solid gray boxes with a surrounding frame, a caption bar, and a variety of clip controls (a context menu, a close button, a minimize button, etc.) Forms can be created quite easily by starting a new project and selecting "Add Form..." from the project menu. If you specify this form as your project's start-up object (from Project / Properties), when you run this code, your form will appear, and the program will end when the form is closed.


Properties of forms

Like all controls, forms have a variety of properties associated with them. Some of these properties can be set at runtime (which we'll cover later) or by modifying them in the Properties Window. To access the Properties Window, simply select the Form (in design mode, of course), and you should see the properties for the form appear in the right-most docking-window directly beneath the Project Explorer. From here, you can change almost every property of your form.

The most important property of a form is its Name. This property can be set only at design, and should appear as the first item in the properties list. You can set this to anything you want; however, it is common convention that all form names begin with a form identifier, such as "Form" or "frm". By default, the first form in a project is named "Form1," the second "Form2," etc. Choosing a clear, descriptive name for your forms is very important because everytime you call methods on or change the properties of a form from runtime, you will use the form's name as an identifier.

Another important property of a form is its Caption. This property specifies what text will be displayed in the form's caption bar. You can change it by selecting "Caption" from the properties list, and then specifying any single line of text you would like. You can adjust the width and height of your forms by either explicitly specifying the property in the Properties Window or by simply resizing the form in design mode. There are many other physical properties of forms that we won't get into here, but please, feel free to play around with them.

Form modules

So far, every VB6 application we've dealt with has been executed from a Basic module (or .bas file), by creating a project, adding a new module, and adding to that module a Public Sub Main(). In traditional BASIC, all programs were constructed this way; however, with the advent of Visual Basic a new kind of module, known as a form module, was introduced. A form module is a unique kind of module that contains code that is owned by one, and only one, form. Every form has one, and only one, form module associated with it, and form modules contain all of the code that can be directly invoked by the form or by controls contained by the form in response to an action by the user. The code in these modules can only be accessed once the form is constructed, and form modules typically contain primarily only Private subroutines and functions, though they may also contain Public helper routines to allow accessibility to components of the form to other modules.

To access a form's code module, simply select the form in the Project Exlporer, righ-click, and select "View Code." This will open up an empty editor window like we're used to seeing with Basic modules--the only difference is what we can put in a form module. The most common starting point for a form is Private Sub Form_Load(). This routine is called immediately after the form is created and drawn, but before the form has begun waiting for user input. To start, let's try rewriting an example you've seen before to use Form_Load() instead of Main():

Private Sub Form_Load()
   MsgBox "Hello, world!"
End Sub

Immediately after this form is loaded, a MsgBox will be displayed with the text "Hello, world!". It is important to note that every form can have a Private Sub Form_Load() and that, unlike with Sub Main, the Form_Load routine can be accessed only by the form module (due to its Private access).

The "Me" identifier [edit]Now let's say we want to access the properties and methods of our form from within our form module. We could use something like Form1.Caption = "Hello, world!", but this is very bad practice, as you'll understand fully once we begin dealing with ActiveX controls and control arrays (much later on!). Instead, Visual Basic provides an identifier known as the "Me" ientifier, which is simialr to "this" in languages such as C and Java. It allows us, basically, to access ourselves--that is, the form module it's used in. For example:

Private Sub Form_Load()
   Me.Caption = "Hello, world!"
End Sub 

This will change the Form's caption to "Hello, world!" after the form is loaded, regardless of what property we specified at design-time.

This VB6 tutorial just scratched the surface on createing a Graphical User Interface (GUI) in Visual Basic 6. However, many tutorials on this site demonstrate different ways of creating a GUI. Take a look around and have some fun. Also just try playing around with controls on your own. If you have any questions or comments related to this VB6 tutorial please post them below. 

This tutorail is released under the GNU Free Documentation License 1.2. The original can be found here.

If you enjoyed this post, subscribe for updates (it's free)

hello, can u please send me

hello,

can u please send me code in vb to create GUI.

Thanks and regards
Sindhura K M

modules

Please give detail explanation about the base and class modules in VB 6

Hey there! I've got a

Hey there!

I've got a question not so much because I've got a problem as such, but rather about
understanding something.

In this tutorial, where you set the MsgBox to the variable "ret", you declare ret as an Integer.
Now I was surprised that this works, because I thought Integer is only used for storing numerical values such as
2 or 5. I was expecting you to declare it as a String, which I was doing, and both ways work perfectly.

I'm very new to Visual Basic, so please excuse such a newbish question,
but I'd like to know why something is working the way it is.

IDE

please,help me with a link where i can download free VB IDE.tanks

vb6 7 segment counter interface

hi i want to know how is this programmed the 7 segment counter....there are 2 buttons the 1st command button is when u click it, it counts 0-9 then the other command button is vice versa...and the number displays correspond to the 7 segment LEDS display
ty

Mind boggled

This site is great and I shall be using it to help me learn VB6 coding hopefully.

Having experimented with VB6 GUI and using some openSC to compile applications , I thought I was doing rather well.

Struggling a little on the beginner tutorials though already after reading them at a glance.

Seems VB6 is a little more complicated than I thought and each tutorial will have to be worked through in depth.

FUNCTION AND SUBROUTINE

first, i would like to say big thank you to the administrators of this great site, i really appreciate. i'm not very clear with the explanations on function and subroutine, i would really appreciate if you could shade light on it.

PROJECT

Can you send me some codes for my banking system its our project in school! with initial balance of 1000 and it has a account number required to open it! and the code is 0254 can you send it to my email thanks! nelson_dalida@yahoo.com

ur answer

take one variable i.e x=0205.

now

function account_number()
dim x as integer
connect to database
if(rs.bof=true and rs.eof=true) then
x=0205
rs!Account_no=x
else
x=rs!Account _no
text1.text=x+1
End function

now go to text box click event

private sub text1_click()
call Account_number
text1.text=val(text1.text)
End sub

after this u will get account number which is just 1 addition of previous one

GUI In VB 6.0

Hi All
I am looking for the "Third Party Software" Tool which can help me in my current Project Development using Visual
Basic 6.0. I wish my form's look, my MDI form's look, my Tool Bar, Status bar, popup all things must be similar to
the Windows 7 User Interface, i would like to amke the Graphical User Interface of my application like Windows
7 or MS Office 2007.
Finally I summarise my needs, i want that kind of tool by usuing that tool i can design my VB forms. If it is
already available in VB then it is really a very big achievement for me, else suggest me which Third Party
Software/Tool i can use complete my implementation.
Waiting for Positive reply
Deepak Shitole
s.deepak150@gmail.com

Graphical - Similar to Flash UI

You can develop an excellent Flash type / Windows 7 type or Office Type UI in Visual Basic 6
But you have to be very familiar in handling images / graphics handling in VB6

Graphics in VB

Can you provide some link to information regarding using images,graphics in application or using flash in vb

about pictures .send me

I need to know about picture and music
whould you learn me

Focus from docs or scanned images

I would like to get help on knowing how to get input into an application which uses VB forms from a scanned image.Like there's an input box by name CustName and we've to get input into it by selecting the cust name from the scanned Delivery receipt etc.

Thanks

Hi,

Iv'e learn a lot from this tutorial. please send me the link on using functions.

thanks.

YOU SUCK

YOU SUCK

LOL U DIK

LOL U DIK

Greate

You people are doing greate job, just do it!

great job

great job

URL under a picture

hello... i was wandering if i could hide a URL (ex: http://s2.battleknight.us/index.php?loc=hire&ref=MjM5MTAz) under a picture... so when someone runs this program and clicks on a picture or on a button maybe his computer opens this link in IE or smth... thanks in advance...

hide a URL? under a picture.

hello... i was wandering if i could hide a URL? under a picture... why hide under when you can hide on-top

over picture use shape then when shape is clicked link it to your web-page by using shell command

LINKS

Hi there...
we all knew that via visual basic can make GUI (graphical user interface). Im just wandering if it is possible to peer devices "PC - USB/firewire/parallel port - machine" using visual basic's GUI, if so how can we adress specific ports.

Thank you!!
IAN

Helpful but can be difficult for beginners

I found the entire tutorial helpful..
Thanks...
but it can be difficult for some w/o much experience in programming , I am referring to this page only.
But if you have a good pick up in programming then it goes very smooth.
Thanks very much for this tutorial , it really helped me.

Nigel Coutinho

Great Tutotial for the Beginners

It is really a great tutorial for the Beginners.... Keep it up. Thanks for your hard work.

Glad you like it. As you

Glad you like it. As you continue to learn, please contribute back to the community. Write a VB6 tutorial for this site.

Its great

I love to read this type of tutorials. I have learnt my VB through tutorials only. I never read a book...

i need a func

i need a function that sets a form on top of all others help pls

...

Not sure how helpful this tutorial is for me. It was generally helpful but failed to mention how to change the text within the buttons on the form-windows (how to change the yes/no/cancel to something else).

I also didn't really follow the forms tutorial. I can't seem to find the forms properties thing even after following the steps given. :\

I found this topic semi

I found this topic semi Useful, while I did learn something new about how to create MsgBoxes the actual code listed does not do anything in VB because there is nothing to Initialize the code. To correct this problem I created a Button using to GUI, and then changed the line "Public Sub Main()" to Public Sub ButtonName_Click()

Example:
Public Sub MsgBox_Click()

Where MsgBox is the name of the button I created

YEAH

this tutorial helps me understand fully what's messagebox and inputbox are all about. thanks

undo code sample?

is there anyone can help me the code of undo?pls

Um...

I didnt find this tutorial very helpful, i copy the codes exactly into VB6 and i get compile errors. Some dont but the ones that dont well they dont do anything ><.

great

I have programmed in different, text based languages like C++ and Java. This tutorial is great for understanding the language. However, I would like to be able to copy code off the web page and use it in a program. Being able to download the example in a program off the site might be nice.

...

Just type the code in yourself instead of copying it, this will also help you learn the language better