Accessing the Windows API in Visual Basic - Calling the API
(Page 5 of 6 )
Place a command Button on your form and set the caption to 'Show Windows Directory'. I am going to assume that the name of this command button has been left as Command1. We will be attaching code to the Click event of this button, so open up the Command1_Click() sub-routine and enter the code below:
Private Sub Command1_Click()
Dim TheResult
Dim TheWindowsDirectory As String
TheWindowsDirectory = Space(144)
'Fill 144 spaces in TheWindowsDirectory string
TheResult = GetWindowsDirectory(TheWindowsDirectory, 144)
'Get path and place it in TheResult string
If TheResult = 0 Then
MsgBox "Cannot get the Windows Directory"
Else
'Prepare the String for preview, and then display in a Message Box
TheWindowsDirectory = Trim(TheWindowsDirectory)
MsgBox "The Windows Path: " & TheWindowsDirectory
End If
End SubRun the program and click on the command button. A messagebox similar to the one shown below should be displayed:

This message box shows that Windows has been installed into the directory (or folder) with the path 'C:\Windows\'. Your box may vary to mine, depending on where Windows has been installed on your computer.
You may be asking yourself why an API function like this would be used. Well, if your project was built to perform a task that has a use for the Windows directory, then you are going to need to know the location of it, and using the API is the easiest way.
If you hard coded the windows directory into your application. then an error may occur, because not all people choose to install Windows to the default c:\windows directory.
There are other API functions available through the same DLL that perform a similar task to the one that we have just coded. For example, 'GetSystemDirectory' will display the full path to the Windows System Directory. In my case, the result would be 'C:\Windows\System', but it may say something different on other systems, depending on where Windows is installed.
Next: Conclusion >>
More Visual Basic Articles
More By Jason Brimblecombe