DllCall

Calls a function inside a DLL, such as a standard Windows API function.

Result := DllCall("DllFile\Function" , Type1, Arg1, Type2, Arg2, "Cdecl ReturnType")

Parameters

Result

DllCall returns the actual value returned by the function. If the function is of a type that does not return a value, the result is an undefined integer. If the function cannot be called due to an error, the return value is blank (an empty string).

[DllFile\]Function

The DLL or EXE file name followed by a backslash and the name of the function. For example: "MyDLL\MyFunction" (the file extension ".dll" is the default when omitted). If an absolute path isn't specified, DllFile is assumed to be in the system's PATH or A_WorkingDir.

DllFile may be omitted when calling a function that resides in User32.dll, Kernel32.dll, ComCtl32.dll, or Gdi32.dll. For example, "User32\IsWindowVisible" produces the same result as "IsWindowVisible".

If no function can be found by the given name, a "W" (Unicode) suffix is automatically appended. For example, "MessageBox" is the same as "MessageBoxW".

Performance can be dramatically improved when making repeated calls to a DLL by loading it beforehand.

This parameter may also consist solely of an integer, which is interpreted as the address of the function to call. Sources of such addresses include COM and RegisterCallback.

Type1, Arg1

Each of these pairs represents a single parameter to be passed to the function. The number of pairs is unlimited. For Type, see the types table below. For Arg, specify the value to be passed to the function.

Cdecl ReturnType

The word Cdecl is normally omitted because most functions use the standard calling convention rather than the "C" calling convention (functions such as wsprintf that accept a varying number of arguments are one exception to this). Note that most object-oriented C++ functions use the thiscall convention, which is not supported.

If present, the word Cdecl should be listed before the return type (if any). Separate each word from the next with a space or tab. For example: "Cdecl Str".

Since a separate "C" calling convention does not exist in 64-bit code, Cdecl may be specified but has no effect on 64-bit builds of AutoHotkey.

ReturnType: If the function returns a 32-bit signed integer (Int), BOOL, or nothing at all, ReturnType may be omitted. Otherwise, specify one of the argument types from the types table below. The asterisk suffix is also supported.

Types of Arguments and Return Values

Str

A string such as "Blue" or MyVar. If the called function modifies the string and the argument is a naked variable, its contents will be updated. For example, the following call would convert the contents of MyVar to uppercase: DllCall("CharUpper", "Str", MyVar).

However, if the function is designed to store a string larger than a variable's current capacity, ensure that the variable is large enough before calling the function. This can be achieved by calling VarSetCapacity(MyVar, 123), where 123 is the length that MyVar must be able to hold.

A Str argument must not be an expression that evaluates to a number (such as i+1). If it is, the function is not called and ErrorLevel is set to -2.

The asterisk variable "Str*" is supported but rarely used. It can be used with functions that expect something like "TCHAR **" or "LPTSTR *".

Note: When passing a string to a function, be aware what type of string the function expects.

WStr Since AutoHotkey uses UTF-16 natively, WStr (wide character string) is equivalent to Str.
AStr

AStr causes the input value to be automatically converted to ANSI. Since the temporary memory used for this conversion is only large enough for the converted input string, any value written to it by the function is discarded. To receive an ANSI string as an output parameter, follow this example:

VarSetCapacity(buf, length)  ; Allocate temporary buffer.
DllCall("Function", "ptr", &buf)  ; Pass buffer to function.
str := StrGet(&buf, "cp0")  ; Retrieve ANSI string from buffer.

See Script Compatibility for equivalent Win32 types and other details.

Int64 A 64-bit integer, whose range is -9223372036854775808 (-0x8000000000000000) to 9223372036854775807 (0x7FFFFFFFFFFFFFFF).
Int

A 32-bit integer (the most common integer type), whose range is -2147483648 (-0x80000000) to 2147483647 (0x7FFFFFFF). An Int is sometimes called a "Long".

An Int should also be used for each BOOL argument expected by a function (a BOOL value should be either 1 or 0).

An unsigned Int (UInt) is also used quite frequently, such as for DWORD.

Short A 16-bit integer, whose range is -32768 (-0x8000) to 32767 (0x7FFF). An unsigned Short (UShort) can be used with functions that expect a WORD.
Char An 8-bit integer, whose range is -128 (-0x80) to 127 (0x7F). An unsigned character (UChar) can be used with functions that expect a BYTE.
Float A 32-bit floating point number, which provides 6 digits of precision.
Double A 64-bit floating point number, which provides 15 digits of precision.
Ptr

A pointer-sized integer, equivalent to Int or Int64 depending on whether the exe running the script is 32-bit or 64-bit. Ptr should be used for pointers to arrays or structures (such as RECT* or LPPOINT) and almost all handles (such as HWND, HBRUSH or HBITMAP). If the parameter is a pointer to a single numeric value such as LPDWORD or int*, generally the * or P suffix should be used instead of "Ptr".

Ptr can also be used with the * or P suffix; it should be used with functions that output a pointer via LPVOID* or similar.

UPtr is also valid, but is only unsigned in 32-bit builds as AutoHotkey does not support unsigned 64-bit integers.

If compatibility with older versions of AutoHotkey is required, use a variable type as shown below:

Ptr := A_PtrSize ? "Ptr" : "UInt" ; If A_PtrSize is not defined, use UInt instead.
DllCall("DeleteFile", Ptr, &filename) ; Omit the quote marks around Ptr.

Note: To pass a NULL handle or pointer, pass the integer 0.

* or P
(suffix)

Append an asterisk (with optional preceding space) to any of the above types to cause the address of the argument to be passed rather than the value itself (the called function must be designed to accept it). Since the value of such an argument might be modified by the function, whenever a naked variable is passed as the argument, that variable's contents will be updated. For example, the following call would pass the contents of MyVar to MyFunction by address, but would also update MyVar to reflect any changes made to it by MyFunction: DllCall("MyDll\MyFunction", "Int*", MyVar).

In general, an asterisk is used whenever a function has an argument type or return type that starts with "LP". The most common example is LPDWORD, which is a pointer to a DWORD. Since a DWORD is an unsigned 32-bit integer, use "UInt*" or "UintP" to represent LPDWORD. An asterisk should not be used for string types such as LPTSTR, pointers to structures such as LPRECT, or arrays; for these, "Str" or "Ptr" should be used, depending on whether you pass a variable or its address.

Note: "Char*" is not the same as "Str" because "Char*" passes the address of an 8-bit number, whereas "Str" passes the address of a series of characters, which may be either 16-bit (Unicode) or 8-bit (for "AStr"), depending on the version of AutoHotkey. Similarly, "UInt*" passes the address of a 32-bit number, so should not be used if the function expects an array of values or a structure larger than 32 bits.

Since variables in AutoHotkey have no fixed type, the address passed to the function points to temporary memory rather than the variable itself. It is not necessary to call VarSetCapacity on the variable as DllCall will update it correctly after the function returns.

U (prefix)

Prepend the letter U to any of the integer types above to interpret it as an unsigned integer (UInt64, UInt, UShort, and UChar). Strictly speaking, this is necessary only for return values and asterisk variables because it does not matter whether an argument passed by value is unsigned or signed (except for Int64).

If a negative integer is specified for an unsigned argument, the integer wraps around into the unsigned domain. For example, when -1 is sent as a UInt, it would become 0xFFFFFFFF.

Unsigned 64-bit integers produced by a function are not supported. Therefore, to work with numbers greater or equal to 0x8000000000000000, omit the U prefix and interpret any negative values received from the function as large integers. For example, a function that yields -1 as an Int64 is really yielding 0xFFFFFFFFFFFFFFFF if it is designed to yield a UInt64.

Note: When specifying an argument type or return type that does not contain a space or asterisk, the quotes around it may be omitted. For example, Str can be used in place of "Str" and CDecl in place of "CDecl". In addition, the letter P may be used in place of asterisk to allow the quotes to be omitted there as well. For example: UIntP.

Errors

DllCall throws an exception under any of the following conditions:

Exceptions and A_LastError

In spite of the built-in exception handling, it is still possible to crash a script with DllCall. This can happen when a function does not directly generate an exception but yields something inappropriate, such as a bad pointer or a string that is not terminated. This might not be the function's fault if the script passed it an unsuitable value such as a bad pointer or a "str" with insufficient capacity. A script can also crash when it specifies an inappropriate argument type or return type, such as claiming that an ordinary integer yielded by a function is an asterisk variable or str.

The built-in variable A_LastError contains the result of the operating system's GetLastError() function, which is called immediately after the function is called (this has no measurable impact on performance). A_LastError is a number between 0 and 4294967295. Like ErrorLevel, A_LastError is a per-thread setting; that is, interruptions by other threads cannot change it. However, A_LastError is also set by Run/RunWait and some other built-in functions.

Performance

When making repeated calls to a DLL, performance can be dramatically improved by loading it explicitly (this is not necessary for a standard DLL such as User32 because it is always resident). This practice avoids the need for DllCall to internally call LoadLibrary and FreeLibrary each time. For example:

hModule := DllCall("LoadLibrary", "Str", "MyFunctions.dll", "Ptr")  ; Avoids the need for DllCall in the loop to load the library.
Loop Files, "C:\My Documents\*.*", "R"
    result := DllCall("MyFunctions\BackupFile", "Str", A_LoopFilePath)
DllCall("FreeLibrary", "Ptr", hModule)  ; To conserve memory, the DLL may be unloaded after using it.

Even faster performance can be achieved by looking up the function's address beforehand. For example:

; In the following example, if the DLL isn't yet loaded, use LoadLibrary in place of GetModuleHandle.
MulDivProc := DllCall("GetProcAddress", Ptr, DllCall("GetModuleHandle", Str, "kernel32", "Ptr"), AStr, "MulDiv", "Ptr")
Loop 500
    DllCall(MulDivProc, Int, 3, Int, 4, Int, 3)

If DllCall's first parameter is a literal string such as "MulDiv" and the DLL containing the function is ordinarily loaded before the script starts, the string is automatically resolved to a function address. This built-in optimization is more effective than the example shown above.

Finally, when passing a string-variable to a function that will not change the length of the string, performance is improved by passing the variable by address (e.g. &MyVar) rather than as a "str" (especially when the string is very long). The following example converts a string to uppercase: DllCall("CharUpper", Ptr, &MyVar, Ptr).

Structures and Arrays

A structure is a collection of members (fields) stored adjacently in memory. Most members tend to be integers.

Functions that accept the address of a structure (or a memory-block array) can be called by storing the structure's raw binary data in a normal variable. The following steps are generally used:

1) Call VarSetCapacity(MyStruct, 123, 0) to ensure that the target variable is large enough to hold the structure's data. Replace 123 with a number that is at least as large as the size of the structure. Specifying zero as the last parameter is optional; it initializes all members to be binary zero, which is typically used to avoid calling NumPut as often in the next step.

2) If the target function uses the values initially in the structure, call NumPut(123, MyStruct, 4, "UInt") to initialize any members that should be non-zero. Replace 123 with the integer to be put into the target member (or specify &Var to store the address of a variable). Replace 4 with the offset of the target member (see step #4 for description of "offset"). Replace "UInt" with the appropriate type or omit it if the member is a pointer or handle.

3) Call the target function, passing the address of MyStruct as a UInt or Ptr argument. For example, DllCall("MyDll\MyFunc", Ptr, &MyStruct). The function will examine and/or change some of the members.

4) Use MyInteger := NumGet(MyStruct, 4, "UInt") to retrieve any desired integers from the structure. Replace 4 with the offset of the target member in the structure. The first member is always at offset 0. The second member is at offset 0 plus the size of the first member (typically 4). Members beyond the second are at the offset of the previous member plus the size of the previous member. Most members -- such as DWORD, Int, and other types of 32-bit integers -- are 4 bytes in size. Replace "UInt" with the appropriate type or omit it if the member is a pointer or handle.

See Structure Examples for actual usages.

Known Limitations

When a variable's address (e.g. &MyVar) is passed to a function and that function alters the length of the variable's contents, subsequent uses of the variable may behave incorrectly. To fix this, do one of the following: 1) Pass MyVar as a "Str" argument rather than as a Ptr/address; 2) Call VarSetCapacity(MyVar, -1) to update the variable's internally-stored length after calling DllCall.

Any binary zero stored in a variable by a function hides all data to the right of the zero; that is, such data cannot be accessed or changed by most built-in functions. However, such data can be manipulated by the address operator and NumPut/NumGet, as well as DllCall itself.

A function that returns the address of one of the strings that was passed into it might return an identical string in a different memory address than expected. For example calling CharLower(CharUpper(MyVar)) in a programming language would convert MyVar's contents to lowercase. But when the same is done with DllCall, MyVar would be uppercase after the following call because CharLower would have operated on a different/temporary string whose contents were identical to MyVar:

MyVar := "ABC"
result := DllCall("CharLower", str, DllCall("CharUpper", Str, MyVar, Str), Str)

To work around this, change the two underlined "Str" values above to Ptr. This interprets CharUpper's return value as a pure address that will get passed as an integer to CharLower.

Certain limitations may be encountered when dealing with strings. For details, see Script Compatibility.

Component Object Model (COM)

COM objects which are accessible to VBScript and similar languages are typically also accessible to AutoHotkey via ComObjCreate, ComObjGet or ComObjActive and the built-in object syntax.

COM objects which don't support IDispatch can be used with DllCall by retrieving the address of a function from the virtual function table of the object's interface. For more details, see the example further below.

Much of the .NET Framework is also accessible via COM and DllCall. See .NET Framework Interop.

Related

Script Compatibility, PostMessage, OnMessage, RegisterCallback, Run, VarSetCapacity, Functions, SysGet, MSDN Library

Examples

; Example: Calls the Windows API function "MessageBox" and report which button the user presses.

WhichButton := DllCall("MessageBox", "Int", "0", "Str", "Press Yes or No", "Str", "Title of box", "Int", 4)
MsgBox "You pressed button #" WhichButton
; Example: Changes the desktop wallpaper to the specified bitmap (.bmp) file.

DllCall("SystemParametersInfo", UInt, 0x14, UInt, 0, Str, A_WinDir . "\winnt.bmp", UInt, 2)
; Example: Calls the API function "IsWindowVisible" to find out if a Notepad window is visible.

DetectHiddenWindows True
if not DllCall("IsWindowVisible", "Ptr", WinExist("Untitled - Notepad"))  ; WinExist returns an HWND.
    MsgBox "The window is not visible."
; Example: Calls the API's wsprintf() to pad the number 432 with leading zeros to make it 10 characters wide (0000000432).

VarSetCapacity(ZeroPaddedNumber, 20)  ; Ensure the variable is large enough to accept the new string.
DllCall("wsprintf", "Str", ZeroPaddedNumber, "Str", "%010d", "Int", 432, "Cdecl")  ; Requires the Cdecl calling convention.
MsgBox ZeroPaddedNumber

; Alterntively, use the Format function in conjunction with the zero flag:
MsgBox Format("{:010}", 432)
; Example: Demonstrates QueryPerformanceCounter(), which gives more precision than A_TickCount's 10ms.

DllCall("QueryPerformanceCounter", "Int64*", CounterBefore)
Sleep 1000
DllCall("QueryPerformanceCounter", "Int64*", CounterAfter)
MsgBox "Elapsed QPC time is " . CounterAfter - CounterBefore
; Example: This is a hotkey that temporarily reduces the mouse cursor's speed, which facilitates precise positioning.
; Hold down the F1 key to slow down the cursor. Release it to return to original speed.

F1::
SPI_GETMOUSESPEED := 0x70
SPI_SETMOUSESPEED := 0x71
; Retrieve the current speed so that it can be restored later:
DllCall("SystemParametersInfo", UInt, SPI_GETMOUSESPEED, UInt, 0, UIntP, OrigMouseSpeed, UInt, 0)
; Now set the mouse to the slower speed specified in the next-to-last parameter (the range is 1-20, 10 is default):
DllCall("SystemParametersInfo", UInt, SPI_SETMOUSESPEED, UInt, 0, Ptr, 3, UInt, 0)
KeyWait "F1"  ; This prevents keyboard auto-repeat from doing the DllCall repeatedly.
return

F1 up::DllCall("SystemParametersInfo", UInt, 0x71, UInt, 0, Ptr, OrigMouseSpeed, UInt, 0)  ; Restore the original speed.
; Example: Monitors the active window and display the position of its vertical scroll bar in its
; focused control (with real-time updates).

SetTimer "WatchScrollBar", 100
return

WatchScrollBar:
ActiveWindow := WinExist("A")
if !ActiveWindow  ; No active window.
    return
FocusedControl := ControlGetFocus()  ; Omit all parameter to use the Last Found Window.
if !FocusedControl  ; No focused control.
    return
; Display the vertical or horizontal scroll bar's position in a ToolTip:
ChildHWND := ControlGetHwnd(FocusedControl)
ToolTip(DllCall("GetScrollPos", "Ptr", ChildHWND, "Int", 1))  ;  Last parameter is 1 for SB_VERT, 0 for SB_HORZ.
return
; Example: This is a working script that writes some text to a file then reads it back into memory.
; This method can be used to help performance in cases where multiple files are being read or written simultaneously.
; Alternatively, FileOpen can be used to the same effect.

FileName := FileSelect("S16",, "Create a new file:")
if FileName = ""
    return
GENERIC_WRITE := 0x40000000  ; Open the file for writing rather than reading.
CREATE_ALWAYS := 2  ; Create new file (overwriting any existing file).
hFile := DllCall("CreateFile", Str, FileName, UInt, GENERIC_WRITE, UInt, 0, Ptr, 0, UInt, CREATE_ALWAYS, UInt, 0, Ptr, 0, Ptr)
if !hFile
{
    MsgBox "Can't open '" FileName "' for writing."
    return
}
TestString := "This is a test string.`r`n"  ; When writing a file this way, use `r`n rather than `n to start a new line.
DllCall("WriteFile", Ptr, hFile, Str, TestString, UInt, StrLen(TestString), UIntP, BytesActuallyWritten, Ptr, 0)
DllCall("CloseHandle", Ptr, hFile)  ; Close the file.

; Now that the file was written, read its contents back into memory.
GENERIC_READ := 0x80000000  ; Open the file for reading rather than writing.
OPEN_EXISTING := 3  ; This mode indicates that the file to be opened must already exist.
FILE_SHARE_READ := 0x1 ; This and the next are whether other processes can open the file while we have it open.
FILE_SHARE_WRITE := 0x2
hFile := DllCall("CreateFile", Str, FileName, UInt, GENERIC_READ, UInt, FILE_SHARE_READ|FILE_SHARE_WRITE, Ptr, 0, UInt, OPEN_EXISTING, UInt, 0, Ptr, 0)
if !hFile
{
    MsgBox "Can't open '" FileName "' for reading."
    return
}
; Make the variable empty for testing purposes, but ensure it retains sufficient capacity:
BytesToRead := VarSetCapacity(TestString, StrLen(TestString))
DllCall("ReadFile", Ptr, hFile, Str, TestString, UInt, BytesToRead, UIntP, BytesActuallyRead, Ptr, 0)
DllCall("CloseHandle", Ptr, hFile)  ; Close the file.
MsgBox "The following string was read from the file: " TestString
; Example: Hides the mouse cursor when you press Win+C. To later show the cursor, press Win+C again.

OnExit(Func("SystemCursor").bind("Show"))  ; Ensure the cursor is made visible when the script exits.

#c::SystemCursor("Toggle")  ; Win+C hotkey to toggle the cursor on and off.

SystemCursor(cmd)  ; cmd = "Show|Hide|Toggle"
{
  static vision := true, c := {}
  static system_cursors := "32512,32513,32514,32515,32516,32642,32643,32644,32645,32646,32648,32649,32650"
  VarSetCapacity(h_cursor, 4444, 1)
  if (cmd = "Reload" or !c.Length())  ; Reload when requested or at first call.
  {
    VarSetCapacity(AndMask, 32*4, 0xFF)
    VarSetCapacity(XorMask, 32*4, 0)
    For i, resID in StrSplit(system_cursors, ",")
    {
      h_cursor := DllCall("LoadCursor", Ptr, 0, Ptr, resID)
      ; System cursors:
      c[i] := {r: resID}
      ; Handles of default cursors:
      c[i][1] := DllCall("CopyImage", Ptr, h_cursor, UInt, 2, Int, 0, Int, 0, UInt, 0)
      ; Blank cursors:
      c[i][0] := DllCall("CreateCursor", Ptr, 0, Int, 0, Int, 0, Int, 32, Int, 32, Ptr, &AndMask, Ptr, &XorMask)
    }
  }
  if (cmd = "Show")
    vision := true
  else if (cmd = "Hide")
    vision := false
  else if (cmd = "Toggle")
    vision := !vision
  else
    return
  For i, cursor in c
  {
    h_cursor := DllCall("CopyImage", Ptr, cursor[vision], UInt, 2, Int, 0, Int, 0, UInt, 0)
    DllCall("SetSystemCursor", Ptr, h_cursor, UInt, cursor.r)
  }
}
; Structure Example: Pass the address of a RECT structure to GetWindowRect(), which sets the structure's
; members to the positions of the left, top, right, and bottom sides of a window (relative to the screen).

Run "Notepad"
WinWait "Untitled - Notepad"  ; This also sets the "last found window" for use with WinExist below.
VarSetCapacity(Rect, 16)  ; A RECT is a struct consisting of four 32-bit integers (i.e. 4*4=16).
DllCall("GetWindowRect", Ptr, WinExist(), Ptr, &Rect)  ; WinExist returns an HWND.
L := NumGet(Rect, 0, "Int"), T := NumGet(Rect, 4, "Int")
R := NumGet(Rect, 8, "Int"), B := NumGet(Rect, 12, "Int")
MsgBox Format("Left {1} Top {2} Right {3} Bottom {4}", L, T, R, B)
; Structure Example: Pass to FillRect() the address of a RECT structure that indicates a part of the
; screen to temporarily paint red.

VarSetCapacity(Rect, 16, 0)  ; Set capacity to hold four 4-byte integers and initialize them all to zero.
NumPut(A_ScreenWidth//2, Rect, 8, "Int")  ; The third integer in the structure is "rect.right".
NumPut(A_ScreenHeight//2, Rect, 12, "Int") ; The fourth integer in the structure is "rect.bottom".
hDC := DllCall("GetDC", "Ptr", 0, "Ptr")  ; Pass zero to get the desktop's device context.
hBrush := DllCall("CreateSolidBrush", "UInt", 0x0000FF, "Ptr")  ; Create a red brush (0x0000FF is in BGR format).
DllCall("FillRect", "Ptr", hDC, "Ptr", &Rect, "Ptr", hBrush)  ; Fill the specified rectangle using the brush above.
DllCall("ReleaseDC", "Ptr", 0, "Ptr", hDC)  ; Clean-up.
DllCall("DeleteObject", "Ptr", hBrush)  ; Clean-up.
; Structure Example: Change the system's clock to the specified date and time. Use caution when
; changing to a date in the future as it may cause scheduled tasks to run prematurely!

SetSystemTime("20051008142211")  ; Pass it a timestamp (local, not UTC).

SetSystemTime(YYYYMMDDHHMISS)
; Sets the system clock to the specified date and time.
; Caller must ensure that the incoming parameter is a valid date-time stamp
; (local time, not UTC). Returns non-zero upon success and zero otherwise.
{
    ; Convert the parameter from local time to UTC for use with SetSystemTime().
    UTC_Delta := DateDiff(A_Now, A_NowUTC, "Seconds")  ; Seconds is more accurate due to rounding issue.
    UTC_Delta := Round(-UTC_Delta/60)  ; Round to nearest minute to ensure accuracy.
    YYYYMMDDHHMISS := DateAdd(YYYYMMDDHHMISS, UTC_Delta, "Minutes")  ; Apply offset to convert to UTC.

    VarSetCapacity(SystemTime, 16, 0)  ; This struct consists of 8 UShorts (i.e. 8*2=16).

    Int := SubStr(YYYYMMDDHHMISS, 1, 4)  ; YYYY (year)
    NumPut(Int, SystemTime, 0, "UShort")
    Int := SubStr(YYYYMMDDHHMISS, 5, 2)  ; MM (month of year, 1-12)
    NumPut(Int, SystemTime, 2, "UShort")
    Int := SubStr(YYYYMMDDHHMISS, 7, 2)  ; DD (day of month)
    NumPut(Int, SystemTime, 6, "UShort")
    Int := SubStr(YYYYMMDDHHMISS, 9, 2)  ; HH (hour in 24-hour time)
    NumPut(Int, SystemTime, 8, "UShort")
    Int := SubStr(YYYYMMDDHHMISS, 11, 2) ; MI (minute)
    NumPut(Int, SystemTime, 10, "UShort")
    Int := SubStr(YYYYMMDDHHMISS, 13, 2) ; SS (second)
    NumPut(Int, SystemTime, 12, "UShort")

    return DllCall("SetSystemTime", Ptr, &SystemTime)
}
/* More Structure Examples:

1) See the WinLIRC client script for a demonstration of how to use DllCall to make a network connection
to a TCP/IP server and receive data from it.

2) The operating system offers standard dialog boxes that prompt the user to pick a font and/or color, or an icon.
These dialogs use structures and are demonstrated at www.autohotkey.com/forum/topic17230.html.

*/
/*
  Example: Temporarily remove the active window from the taskbar by using COM.

  Methods in ITaskbarList's VTable:
    IUnknown:
      0 QueryInterface  -- use ComObjQuery instead
      1 AddRef          -- use ObjAddRef instead
      2 Release         -- use ObjRelease instead
    ITaskbarList:
      3 HrInit
      4 AddTab
      5 DeleteTab
      6 ActivateTab
      7 SetActiveAlt
*/
IID_ITaskbarList  := "{56FDF342-FD6D-11d0-958A-006097C9A090}"
CLSID_TaskbarList := "{56FDF344-FD6D-11d0-958A-006097C9A090}"

; Create the TaskbarList object and store its address in tbl.
tbl := ComObjCreate(CLSID_TaskbarList, IID_ITaskbarList)

activeHwnd := WinExist("A")

DllCall(vtable(tbl,3), "ptr", tbl)                     ; tbl.HrInit()
DllCall(vtable(tbl,5), "ptr", tbl, "ptr", activeHwnd)  ; tbl.DeleteTab(activeHwnd)
Sleep 3000
DllCall(vtable(tbl,4), "ptr", tbl, "ptr", activeHwnd)  ; tbl.AddTab(activeHwnd)

; Non-dispatch objects must always be manually freed.
ObjRelease(tbl)

vtable(ptr, n) {
    ; NumGet(ptr+0) returns the address of the object's virtual function
    ; table (vtable for short). The remainder of the expression retrieves
    ; the address of the nth function's address from the vtable.
    return NumGet(NumGet(ptr+0), n*A_PtrSize)
}