....... |
Using Windows API in VB Tutorial Passing Parameters |
||
Of course you know how to pass parameters, just put it in the function call and its done! Well there are some details you should be aware of when passing parameters to API function. ByVal or ByRef. Usually you don't have to bother about these keywords as VB API Text Viewer declares the function parameters as API wants them and when you just enter your value, it is passed as is declared. Generally, when a value is passed ByVal, the actual value is passed directly to the function, and when passed ByRef, the address of the value is passed. The only thing you may encounter is the Any type. Passing strings to API function isn't difficult too. The API expects the address of the first character of the string and reads ahead of this address till it reaches a Null character. Sound bad, but this the way VB actually handles strings. The only thing to remember is always to pass the String ByRef. The situation is slightly different when you expect some information to be returned by the function. Here is the declaration of GetComputerName API function: Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long The first parameter is a long pointer to string, and the second the length of the string. If you just declare a variable as String and pass it to this function, an error occurs. So, you need to initialize the string first. Here is how to get the computer name: Dim
Buffer As String Here, the string is initialized as 255-space string. We pass it to the function and give it the length too. The function returns 0 for an error or the actual length of the computer name otherwise. CompName$ will contain the computer name. Some functions also expect arrays. Here is an example (to try it, paste all the code in a form module with a command button on it): Private Declare Function SetSysColors Lib "user32" Alias "SetSysColors" (ByVal nChanges As Long, lpSysColor As Long, lpColorValues As Long) As Long The last two parameter are arrays of Long. To pass an array to a function, you pass just the first element. Here is a sample code: Private
Const COLOR_ACTIVECAPTION = 2 Private
Sub Command1_Click() SysColor(0)
= COLOR_ACTIVECAPTION ColorValues(0)
= RGB(58, 158, 58) 'dark green Ret&
= SetSysColors(4&, SysColor(0), ColorValues(0)) This sample changes the system colors for the active window caption background and text and for the inactive window caption background and text. |
|||