Friday, September 25, 2015

VbScript to call windows API Functions (user32 dll)

We can make use excel object and ExecuteExcel4Macro method to call User32 DLL methods.

Below is the syntax:

CALL(dll_name, function_name, type_string, func_arguments1, ..., func_argumentsN)

dll_name - the name of the DLL, which contains the desired function. This name must contain the full path if the DLL is not located in your Windows, System folder, or the folder specified in the environment variable PATH.
function_name - name of the function.
type_string - text string that identifies the data type of the return value and the data types of all parameters. The first character type_string defines the return value.
func_arguments1, ..., func_argumentsN - function parameters. Their types must comply type_string. It may be transmitted up to 27 parameters.
Data types for type_string:
B - 8-byte floating-point number (IEEE), Transferred by Value, C type double.
C - Zero (null) terminated string (max. Length = 255 characters), Transferred by Reference, C type char *
F - Zero (null) terminated string (max. Length = 255 characters), Transferred by Reference (modify in place), C type char *
J - 4 bytes wide signed integer, Transferred by Value, C type long int
P - Excel's OPER data structure, Transferred by Reference, C type OPER *
R - Excel's XLOPER data structure, Transferred by Reference, C type XLOPER *
Examples:

Dim hwnd

CreateObject("WScript.Shell").Run "notepad", 1, False
With CreateObject("Excel.Application")
 hwnd = .ExecuteExcel4Macro("CALL(""user32"", ""FindWindowA"", ""JCJ"", ""Notepad"", 0)")
 If hwnd = 0 Then
  wscript.echo "note pad window not found"
  WScript.Quit
 Else
  wscript.echo "note pad window found"

  Excel.ExecuteExcel4Macro "CALL(""user32"",""ShowWindow"",""JJJ""," & hwnd & ","& SW_
RESTORE
&")"

 End If
end with

*********************************************************
some other uses:
  GetPIDByHWND = excel.ExecuteExcel4Macro("CALL(""user32"", ""GetWindowThreadProcessId"", ""2JN"", " & CStr(hwnd) & ", 0)")
  hwnd = excel.ExecuteExcel4Macro("CALL(""user32"", ""GetDesktopWindow"", ""J"")")
  hwnd = excel.ExecuteExcel4Macro("CALL(""user32"", ""GetWindow"", ""JJJ"", " & CStr(hwnd) & ", 5)")
' Puts the cursor at the specified X and Y corrdinates
  Excel.ExecuteExcel4Macro("CALL(""user32"",""SetCursorPos"",""JJJ""," & x & "," & y & ")")