Wrapping String Functions
Although passing vbNullString as a string argument is a vast improvement, it’s still un-Basic. The Basic Way to signal that a string should be ignored is to use optional parameters. Before Visual Basic version 4, you couldn’t define your own optional parameters, although you could fake them by using an empty string as a signal to ignore the argument. For example, you could write a wrapper function that worked as follows:
hWnd = VB3FindWindow(“", “Calculator”)
hWnd = VB3FindWindow(“SciCalc", ““)
hWnd = VB3FindWindow(“SciCalc", “Calculator”)
Visual Basic version 5 not only allows optional parameters but also lets you assign them by name. You can write a function that can be called as shown here:
hWnd = VBFindWindow(, “Calculator”)
hWnd = VBFindWindow(“SciCalc”)
hWnd = VBFindWindow(“SciCalc", “Calculator”)
hWnd = VBFindWindow(Title:="Calculator”)
hWnd = VBFindWindow(Class:="SciCalc”)
The code for this function is simple:
Function VBFindWindow(Optional Class As String, _
Optional Title As String) As Long
VBFindWindow = FindWindow(Class, Title)
End Function
This version uses the new typed optional argument syntax available in Visual Basic version 5. Version 4 supported optional arguments only for Variants. The syntax was more complicated and the performance worse because of Variant conversions. Normally, I would initialize the default arguments for clarity:
Optional Class As String = vbNullString
Unfortunately, Visual Basic won’t let you do that for strings. It appears to work during debugging, but fails when you try to build a compatible ActiveX component. Fortunately, vbNullString is the default value for strings, so leaving it out does no harm except to readability. You could achieve the same effect by using optional arguments in a Declare statement:
Declare Function FindWindow Lib "USER32" Alias "FindWindowA" ( _
Optional ByVal Class As String, _
Optional ByVal Title As String) As Long
However, you can’t write an equivalent type library entry, so VBFindWindow is the only way to provide a standard version so that you don’t have to insert the Declare statement in every project.
NOTE I don’t use my normal Hungarian naming convention for optional arguments. Since optional arguments can be omitted or given out-of-order by name, they are part of the public interface. It’s rude to impose your private naming convention on parameter names or properties that might be used by other programmers who don’t share your conventions.