Programming Tips & Tricks #0008
Visual Basic Command Line Arguments
I recently received an email from a reader who wanted to know if its possible to run a Visual Basic executable program with command line arguments. The answer is yes, although this feature is not as robust as it is with executables compiled with other languages such as C.
What's a command line argument, you might ask?
Let me give you an example. Suppose you want to execute a program whose main form obtains its caption from an argument supplied by the user when the program is executed.
You can take advantage of Visual Basic's Command function, which returns a value equal to the argument supplied after the name of the Visual Basic executable. For instance, if the name of your executable is Test.exe, if you type this value into the Windows Start-Run dialog
Test.exe VB
and enter this code into the Load Event Procedure of the Startup Form
Private Sub Form_Load()
If Command <> "" Then
Form1.Caption = Command
End If
End Sub
when your form appears, "VB" will appear in the form's caption. Notice that we first check to see if the return value of the Command function is equal to an empty string, which will be the case if the user executes your program with no arguments.
Invariably, the next question that is asked is whether you can supply more than one argument to the executable. Other languages, such as C, populate multiple command line arguments separated by spaces into an argument array that is available to the program when it executes.
In Visual Basic, however, everything that appears after the name of the executable is considered a single string argument. Separating multiple arguments with commas, quotation marks, or other delimiters won't affect that--everything after the executable name is considered a single string argument and is returned as a single string from the Command Function.
For instance, typing this statement into the Start-Run Dialog Box
Test.exe I,love,VB
results in the form's caption being set to "I,love,VB".
However, with a little imagination and some string manipulation, it isn't difficult to come up with a workaround to this restriction.
Showing posts with label Programming Tips. Show all posts
Showing posts with label Programming Tips. Show all posts
Monday, July 31, 2000
Monday, July 24, 2000
Programming Tips & Tricks #0007---Global Keyboard Handler in Visual Basic
Tips & Tricks #0007
Global Keyboard Handler in Visual Basic
One of the questions that I am frequently asked is how to implement Keystroke validation in a Visual Basic Textbox. The answer is that you can insert code into the KeyPress Event Procedure of a Textbox--and implement Keystroke validation that way. For instance, this code will ensure that only numbers are entered into a Textbox---it also permits the user to press enter a BackSpace key in case they make a mistake.
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 8 Then Exit Sub '8 is Backspace
If KeyAscii <> 57 Then 'Range of numeric values
KeyAscii = 0
End If
End Sub
Entering code into the KeyPress Event Procedure of a Textbox is fine for one or two Textboxes---but If you have a large number of Textboxes on your form, this is not an enviable task. In that case, you have two alternatives:
First, you can make each Textbox a member of a Textbox Control Array, in which case each Textbox 'shares' the same KeyPress Event Procedure. Sharing code like that is the chief benefit of a Control Array.
The second alternative is to set up a Form Level or Global Keyboard Handler by telling Visual Basic that you want the Form's KeyPress Event Procedure to be triggered BEFORE the individual Textbox KeyPress Event Procedures.
You do this by setting the KeyPreview Property of the Form to True. This will cause the KeyPress Event Procedure of the Form to be triggered whenever a keystroke is made for any of the Textboxes on the form. What that means is that you can take the code you write for each Textbox KeyPress Event on your form--and place it in just one place---the KeyPress Event Procedure of the Form.
Global Keyboard Handler in Visual Basic
One of the questions that I am frequently asked is how to implement Keystroke validation in a Visual Basic Textbox. The answer is that you can insert code into the KeyPress Event Procedure of a Textbox--and implement Keystroke validation that way. For instance, this code will ensure that only numbers are entered into a Textbox---it also permits the user to press enter a BackSpace key in case they make a mistake.
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 8 Then Exit Sub '8 is Backspace
If KeyAscii <> 57 Then 'Range of numeric values
KeyAscii = 0
End If
End Sub
Entering code into the KeyPress Event Procedure of a Textbox is fine for one or two Textboxes---but If you have a large number of Textboxes on your form, this is not an enviable task. In that case, you have two alternatives:
First, you can make each Textbox a member of a Textbox Control Array, in which case each Textbox 'shares' the same KeyPress Event Procedure. Sharing code like that is the chief benefit of a Control Array.
The second alternative is to set up a Form Level or Global Keyboard Handler by telling Visual Basic that you want the Form's KeyPress Event Procedure to be triggered BEFORE the individual Textbox KeyPress Event Procedures.
You do this by setting the KeyPreview Property of the Form to True. This will cause the KeyPress Event Procedure of the Form to be triggered whenever a keystroke is made for any of the Textboxes on the form. What that means is that you can take the code you write for each Textbox KeyPress Event on your form--and place it in just one place---the KeyPress Event Procedure of the Form.
Monday, July 10, 2000
Programming Tips & Tricks #0006---Named Visual Basic Arguments
Tips & Tricks #0006
Named Visual Basic Arguments
One of the themes I emphasize in my computer classes over and over again is the importance of writing code that is readable---that is, code that other programmers and developers will be able to understand, and if necessary, easily modify in the future. Some obvious ways to write readable code include the use of program comments in your code---no matter what the language you are using to develop your program, all major languages provide for comments. Something else that can make your Visual Basic more readable is the user of Named Arguments.
Let me illustrate by executing the Visual Basic MsgBox Function to display a Windows Message Box. The Visual Basic MsgBox function has one required argument (Prompt), and four optional arguments (Buttons, Title, HelpFile and Context).
MsgBox “I love Visual Basic”
By default, this code will display a Message Box with a single command button captioned OK, with the text “I love Visual Basic”, and the Visual Basic Project name displayed in the Title Bar of the Message Box.
Suppose I’m not happy with the default Title in the Message Box, and I decide I want to customize it. Doing this is easy—all I need to do is supply the Title argument to the MsgBox function. However, since Title is the third argument, I either need to supply the second argument---Buttons, which is by default presumed to be the value vbOKOnly---or provide a ‘comma placeholder’, like this.
MsgBox “I love Visual Basic”,, “SearchVB.Com”
Notice the two commas back-to-back, with no value in-between. This is the ‘comma placeholder’ and is how we tell VB that although we have a value for the third argument, we have no explicit value for the second argument.
When we execute this code, we’ll see a Message Box that reads “I love Visual Basic”, and that has “SearchVB.Com” for its Title Bar.
Named Arguments can make passing optional arguments easier—and make your code infinitely easier to read and modify. For instance, the code we wrote above can be re-written to this using Named Arguments.
MsgBox Prompt:="I love Visual Basic", Title:="SearchVB.Com"
With Named Arguments, we specify the name of the argument, followed by a colon and equals sign (:=), then the value for the argument. By using Named Arguments, we don’t need to provide a ‘comma placeholder’ for the second argument Buttons. Since we are naming the argument, VB knows that ‘SearchVB.Com’ is the value for the Optional Argument ‘Title’. And since we name the arguments, being able to read and understand the code in the future is much easier.
Named Visual Basic Arguments
One of the themes I emphasize in my computer classes over and over again is the importance of writing code that is readable---that is, code that other programmers and developers will be able to understand, and if necessary, easily modify in the future. Some obvious ways to write readable code include the use of program comments in your code---no matter what the language you are using to develop your program, all major languages provide for comments. Something else that can make your Visual Basic more readable is the user of Named Arguments.
Let me illustrate by executing the Visual Basic MsgBox Function to display a Windows Message Box. The Visual Basic MsgBox function has one required argument (Prompt), and four optional arguments (Buttons, Title, HelpFile and Context).
MsgBox “I love Visual Basic”
By default, this code will display a Message Box with a single command button captioned OK, with the text “I love Visual Basic”, and the Visual Basic Project name displayed in the Title Bar of the Message Box.
Suppose I’m not happy with the default Title in the Message Box, and I decide I want to customize it. Doing this is easy—all I need to do is supply the Title argument to the MsgBox function. However, since Title is the third argument, I either need to supply the second argument---Buttons, which is by default presumed to be the value vbOKOnly---or provide a ‘comma placeholder’, like this.
MsgBox “I love Visual Basic”,, “SearchVB.Com”
Notice the two commas back-to-back, with no value in-between. This is the ‘comma placeholder’ and is how we tell VB that although we have a value for the third argument, we have no explicit value for the second argument.
When we execute this code, we’ll see a Message Box that reads “I love Visual Basic”, and that has “SearchVB.Com” for its Title Bar.
Named Arguments can make passing optional arguments easier—and make your code infinitely easier to read and modify. For instance, the code we wrote above can be re-written to this using Named Arguments.
MsgBox Prompt:="I love Visual Basic", Title:="SearchVB.Com"
With Named Arguments, we specify the name of the argument, followed by a colon and equals sign (:=), then the value for the argument. By using Named Arguments, we don’t need to provide a ‘comma placeholder’ for the second argument Buttons. Since we are naming the argument, VB knows that ‘SearchVB.Com’ is the value for the Optional Argument ‘Title’. And since we name the arguments, being able to read and understand the code in the future is much easier.
Monday, June 26, 2000
Programming Tips & Tricks #0005---With...EndWith in VB
Tips & Tricks #0005
In my consulting practice, I frequently see examples of Visual Basic code that could be improved upon, either from a readability point of view or from an efficiency point of view. Today I'd like to discuss a relatively new Visual Basic construct that can improve both the readability and efficiency of your code---and save you quite a few keystrokes in the process. That construct is the With…End With statement.
The With…End With statement allows you to 'bundle' Property and Method calls to a single object within the With…End With block. For instance, here's some code that sets the properties of a Command Button, and then executes its Move Method.
Private Sub Form_Load()
Command1.Caption = "OK"
Command1.Visible = True
Command1.Top = 200
Command1.Left = 5000
Command1.Enabled = True
Command1.Move 1000,1000
End Sub
By using the With…End With statement, we can eliminate quite a few programmer keystrokes, and make the code a bit more readable in the process---like this…
Private Sub Form_Load()
With Command1
.Caption = "OK"
.Visible = True
.Top = 200
.Left = 5000
.Enabled = True
.Move 1000,1000
End With
End Sub
Not only have we reduced the number of keystrokes in the procedure, but using the With…End With construct produces more efficient code.
Each reference to an object's property or method requires a Registry 'look up' to execute the code statement---by using the With…End With statement, VB is able to 'pool' this lookup into a single Input Output operation---thereby making your program run faster.
The bottom line---whenever you find yourself coding multiple operations against an Object, use the With…End With statement.
In my consulting practice, I frequently see examples of Visual Basic code that could be improved upon, either from a readability point of view or from an efficiency point of view. Today I'd like to discuss a relatively new Visual Basic construct that can improve both the readability and efficiency of your code---and save you quite a few keystrokes in the process. That construct is the With…End With statement.
The With…End With statement allows you to 'bundle' Property and Method calls to a single object within the With…End With block. For instance, here's some code that sets the properties of a Command Button, and then executes its Move Method.
Private Sub Form_Load()
Command1.Caption = "OK"
Command1.Visible = True
Command1.Top = 200
Command1.Left = 5000
Command1.Enabled = True
Command1.Move 1000,1000
End Sub
By using the With…End With statement, we can eliminate quite a few programmer keystrokes, and make the code a bit more readable in the process---like this…
Private Sub Form_Load()
With Command1
.Caption = "OK"
.Visible = True
.Top = 200
.Left = 5000
.Enabled = True
.Move 1000,1000
End With
End Sub
Not only have we reduced the number of keystrokes in the procedure, but using the With…End With construct produces more efficient code.
Each reference to an object's property or method requires a Registry 'look up' to execute the code statement---by using the With…End With statement, VB is able to 'pool' this lookup into a single Input Output operation---thereby making your program run faster.
The bottom line---whenever you find yourself coding multiple operations against an Object, use the With…End With statement.
Monday, May 29, 2000
Programming Tips & Tricks #0003---Changing Control names in VB6
Tips & Tricks #0003
Have you ever wished you had named a Visual Basic control by another name—or come across a project where the original programmer accepted all of the default control names—such as Command1, List1, Text1, etc.
Changing the name of a control is easy---you just need to open up the Properties Window for that control and change the Name property. However, what happens to the code associated with that control won’t make you happy!
The code seems to disappear---in actuality, any event procedure associated with the originally named control is relegated to the General Declarations Section of the form. As a result, when you run your program, that code is never executed.
So how do you “get the code back”?
The code hasn’t really gone away---all you need to do is find the event procedure in the General Declarations Section of the form—and then change the “control name” portion of the Procedure header to the new name of the control.
For instance, if you had this code in the Click Event procedure of a Command Button named Command1…
Private Sub Command1_Click()
Msgbox “I love VB”
End Sub
and then renamed the control to cmdOK---VB ‘moves’ this code to the General Declarations Section of the Form.
All you need to do is modify the procedure so that it looks like this…
Private Sub cmdOK_Click()
Msgbox “I love VB”
End Sub
Now, VB will once again associate this code with the command button---and when you run your program, the code will execute---just like before.
By the way, some of my fellow programmers rename their event procedures prior to changing the name of the control. Either way, the effect is still the same---the code will be associated with the newly named control.
Have you ever wished you had named a Visual Basic control by another name—or come across a project where the original programmer accepted all of the default control names—such as Command1, List1, Text1, etc.
Changing the name of a control is easy---you just need to open up the Properties Window for that control and change the Name property. However, what happens to the code associated with that control won’t make you happy!
The code seems to disappear---in actuality, any event procedure associated with the originally named control is relegated to the General Declarations Section of the form. As a result, when you run your program, that code is never executed.
So how do you “get the code back”?
The code hasn’t really gone away---all you need to do is find the event procedure in the General Declarations Section of the form—and then change the “control name” portion of the Procedure header to the new name of the control.
For instance, if you had this code in the Click Event procedure of a Command Button named Command1…
Private Sub Command1_Click()
Msgbox “I love VB”
End Sub
and then renamed the control to cmdOK---VB ‘moves’ this code to the General Declarations Section of the Form.
All you need to do is modify the procedure so that it looks like this…
Private Sub cmdOK_Click()
Msgbox “I love VB”
End Sub
Now, VB will once again associate this code with the command button---and when you run your program, the code will execute---just like before.
By the way, some of my fellow programmers rename their event procedures prior to changing the name of the control. Either way, the effect is still the same---the code will be associated with the newly named control.
Monday, May 15, 2000
Programming Tips & Tricks #0002---Enforcing Variable Declaration in your VB program
Tips & Tricks #0002
In a previous article, I mentioned the importance of enforcing Variable Declaration in your Visual Basic program by ensuring that ‘Option Explicit’ is coded in the General Declarations Section of each module in your project.
Most high level programming languages force the developer to explicitly declare a variable before using it. Visual Basic is a notable exception. In fact, by default, VB’s installation leaves the Visual Basic environment in a state where variable declaration is NOT required.
After installing Visual Basic, immediately select Tools-Options and check ON
Require Variable Declaration
Selecting this option causes Visual Basic to insert this statement
Option Explicit
into the General Declarations Section of each module in your project. The result is that an attempt to refer to a variable in code without first declaring it results in a compiler error.
What’s the big deal, you might ask? Is there really a harm in leaving this option checked off? Suppose you use a variable in code that you haven't declared? Visual Basic is a programmer friendly language—won’t VB take care of it?
The answer is yes---VB will take care of it---but the price of a mistake on your part can be huge.
For instance, suppose you assign a value to a variable called sngUnitPrice like this…
sngUnitPrice = 13.48
and then later in your code you attempt to refer to this variable in a calculation, but accidentally refer to it by an incorrect name, for instance sngUnitCost (yes, it can happen!)
sngTotalPrice = sngUnitCost * m_intQuantity
You're expecting the program to come up with a valid price--instead, the result will be zero, since the value of the incorrectly named variable sngUnitCost is zero!
When you tell VB to enforce variable declaration, errors like this are caught at compile time---potentially preventing disastrous results form occurring.
In a previous article, I mentioned the importance of enforcing Variable Declaration in your Visual Basic program by ensuring that ‘Option Explicit’ is coded in the General Declarations Section of each module in your project.
Most high level programming languages force the developer to explicitly declare a variable before using it. Visual Basic is a notable exception. In fact, by default, VB’s installation leaves the Visual Basic environment in a state where variable declaration is NOT required.
After installing Visual Basic, immediately select Tools-Options and check ON
Require Variable Declaration
Selecting this option causes Visual Basic to insert this statement
Option Explicit
into the General Declarations Section of each module in your project. The result is that an attempt to refer to a variable in code without first declaring it results in a compiler error.
What’s the big deal, you might ask? Is there really a harm in leaving this option checked off? Suppose you use a variable in code that you haven't declared? Visual Basic is a programmer friendly language—won’t VB take care of it?
The answer is yes---VB will take care of it---but the price of a mistake on your part can be huge.
For instance, suppose you assign a value to a variable called sngUnitPrice like this…
sngUnitPrice = 13.48
and then later in your code you attempt to refer to this variable in a calculation, but accidentally refer to it by an incorrect name, for instance sngUnitCost (yes, it can happen!)
sngTotalPrice = sngUnitCost * m_intQuantity
You're expecting the program to come up with a valid price--instead, the result will be zero, since the value of the incorrectly named variable sngUnitCost is zero!
When you tell VB to enforce variable declaration, errors like this are caught at compile time---potentially preventing disastrous results form occurring.
Friday, April 28, 2000
Programming Tips & Tricks #0001---Working with someone else’s code
Tips & Tricks
Working with someone else’s code
The scenario (all too familiar):
You have a new job, and your first programming assignment is to modify a Visual Basic program that was written by another programmer who has left the company. The program is hard to follow. It has no comments, all of the variables are haphazardly named, and all the forms and controls were left with their default names, such as Form1, Form2, Command1, Option1, etc. You’re overwhelmed.
This is not an unusual feeling. In fact, you can feel the same way about your own code a year or so after writing it. So I emphasize these precautionary measures to ensure easy comprehension by others:
1. Option Explicit is coded in all of your modules (this ensures that Visual Basic enforces that all variables are declared before using them)
2. All variables and controls are named using a formal naming convention (i.e. Hungarian Notation)---this makes modifying the program somewhere down the road much easier
3. Code that is repetitive in nature is consolidated into procedures and called from within the program
4. Every module has comments describing its major functions and features
5. Code that is anything out of the ordinary is also commented
Sounds great, but how do these ‘rules’ help you modify someone else’s code? Unfortunately, I’m suggesting you correct the mistakes of the past.
Of course, before you do this, you need to get your supervisor or project leader to ‘buy into’ that plan. Obviously, if he or she is expecting the program modification to be made in about an hour, so taking a week to clean the code and make the modification won’t make you a hit in the Employee cafeteria.
However, I can almost assure you this won’t be the last time this program is modified. Biting the bullet now and cleaning it up will make things much easier on the next junior programmer who finds himself in the uncomfortable position of modifying this code.
Once you have the go-ahead to proceed, the first thing to do is to ensure that Option Explicit is coded in the General Declarations Section of every module in the program. -- if it’s not, add it manually -- and then run the program. Guess what? The program no longer runs. Why?
Coding Option Explicit will cause VB to mark, as a syntax error, every instance of a variable that hasn’t been declared---potentially lethal errors in a program. At this point, you need to identify the variables that haven’t been declared, and explicitly declare them, with a defined type (i.e. Integer, String, Date). While you’re at it, this wouldn’t be a bad time to rename variables using either Hungarian Naming Convention, or a naming convention in use at your company. Using Visual Basic’s Search and Replace features can make this task a lot easier than it sounds.
With all of the variables properly declared and named properly, now is a good time to name those forms and controls in a meaningful way. Keep in mind that when you change the name of a control, the code associated with it can appear to be ‘lost,’ finding its way into the General Declarations Section. To avoid this, first rename any event procedures associated with the control manually with the new name of the control—then bring up the Properties Window for the control and change its Name property there.
At this point, make sure the program runs okay. You’ll find you now have an understanding of how the program works -- so much so, that you should be able to identify code that can be centralized in a subprocedure or function. Along the way, insert comments in your code explaining what’s going on. Write those custom procedures and place them in either a Form Module or a Standard Module (every Visual Basic program I write has one).
Now, with the Visual Basic program nicely sanitized, it’s time to code that simple modification you’ve been asked to make. Hopefully it will be a piece of cake.
Working with someone else’s code
The scenario (all too familiar):
You have a new job, and your first programming assignment is to modify a Visual Basic program that was written by another programmer who has left the company. The program is hard to follow. It has no comments, all of the variables are haphazardly named, and all the forms and controls were left with their default names, such as Form1, Form2, Command1, Option1, etc. You’re overwhelmed.
This is not an unusual feeling. In fact, you can feel the same way about your own code a year or so after writing it. So I emphasize these precautionary measures to ensure easy comprehension by others:
1. Option Explicit is coded in all of your modules (this ensures that Visual Basic enforces that all variables are declared before using them)
2. All variables and controls are named using a formal naming convention (i.e. Hungarian Notation)---this makes modifying the program somewhere down the road much easier
3. Code that is repetitive in nature is consolidated into procedures and called from within the program
4. Every module has comments describing its major functions and features
5. Code that is anything out of the ordinary is also commented
Sounds great, but how do these ‘rules’ help you modify someone else’s code? Unfortunately, I’m suggesting you correct the mistakes of the past.
Of course, before you do this, you need to get your supervisor or project leader to ‘buy into’ that plan. Obviously, if he or she is expecting the program modification to be made in about an hour, so taking a week to clean the code and make the modification won’t make you a hit in the Employee cafeteria.
However, I can almost assure you this won’t be the last time this program is modified. Biting the bullet now and cleaning it up will make things much easier on the next junior programmer who finds himself in the uncomfortable position of modifying this code.
Once you have the go-ahead to proceed, the first thing to do is to ensure that Option Explicit is coded in the General Declarations Section of every module in the program. -- if it’s not, add it manually -- and then run the program. Guess what? The program no longer runs. Why?
Coding Option Explicit will cause VB to mark, as a syntax error, every instance of a variable that hasn’t been declared---potentially lethal errors in a program. At this point, you need to identify the variables that haven’t been declared, and explicitly declare them, with a defined type (i.e. Integer, String, Date). While you’re at it, this wouldn’t be a bad time to rename variables using either Hungarian Naming Convention, or a naming convention in use at your company. Using Visual Basic’s Search and Replace features can make this task a lot easier than it sounds.
With all of the variables properly declared and named properly, now is a good time to name those forms and controls in a meaningful way. Keep in mind that when you change the name of a control, the code associated with it can appear to be ‘lost,’ finding its way into the General Declarations Section. To avoid this, first rename any event procedures associated with the control manually with the new name of the control—then bring up the Properties Window for the control and change its Name property there.
At this point, make sure the program runs okay. You’ll find you now have an understanding of how the program works -- so much so, that you should be able to identify code that can be centralized in a subprocedure or function. Along the way, insert comments in your code explaining what’s going on. Write those custom procedures and place them in either a Form Module or a Standard Module (every Visual Basic program I write has one).
Now, with the Visual Basic program nicely sanitized, it’s time to code that simple modification you’ve been asked to make. Hopefully it will be a piece of cake.
Subscribe to:
Posts (Atom)