PageRenderTime 56ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/AutoHotkey.docset/Contents/Resources/Documents/commands/DllCall.htm

https://gitlab.com/ahkscript/Autohotkey.docset
HTML | 419 lines | 357 code | 62 blank | 0 comment | 0 complexity | 05ec69e1a946eaa80e2a7c38c5b330ca MD5 | raw file
  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>DllCall</title>
  5. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  6. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7. <link href="../static/theme.css" rel="stylesheet" type="text/css" />
  8. <script src="../static/content.js" type="text/javascript"></script>
  9. </head>
  10. <body>
  11. <h1>DllCall()</h1>
  12. <p>Calls a function inside a DLL, such as a standard Windows API function.</p>
  13. <pre class="Syntax">Result := DllCall(&quot;[DllFile\]Function&quot; [, Type1, Arg1, Type2, Arg2, &quot;Cdecl ReturnType&quot;])</pre>
  14. <h3>Parameters</h3>
  15. <dl>
  16. <dt>Result</dt>
  17. <dd><p>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 <a href="#error">error</a>, the return value is blank (an empty string).</p></dd>
  18. <dt>[DllFile\]Function</dt>
  19. <dd><p>The DLL or EXE file name followed by a backslash and the name of the function. For example: <code>&quot;MyDLL\MyFunction&quot;</code> (the file extension &quot;.dll&quot; is the default when omitted). If an absolute path isn't specified, <em>DllFile</em> is assumed to be in the system's PATH or <a href="../Variables.htm#WorkingDir">A_WorkingDir</a>.</p>
  20. <p id="std"><em>DllFile</em> may be omitted when calling a function that resides in User32.dll, Kernel32.dll, ComCtl32.dll, or Gdi32.dll. For example, <code>&quot;User32\IsWindowVisible&quot;</code> produces the same result as <code>&quot;IsWindowVisible&quot;</code>.</p>
  21. <p>If no function can be found by the given name, an A (ANSI) or W (Unicode) suffix is automatically appended based on which version of AutoHotkey is running the script. For example, <code>&quot;MessageBox&quot;</code> is the same as <code>&quot;MessageBoxA&quot;</code> in ANSI versions and <code>&quot;MessageBoxW&quot;</code> in Unicode versions.</p>
  22. <p>Performance can be dramatically improved when making <em>repeated</em> calls to a DLL by <a href="#load">loading it beforehand</a>.</p>
  23. <p>In v1.0.46.08+, 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 <a href="#COM">COM</a> and <a href="RegisterCallback.htm">RegisterCallback()</a>.</p></dd>
  24. <dt>Type1, Arg1</dt>
  25. <dd><p>Each of these pairs represents a single parameter to be passed to the function. The number of pairs is unlimited. For <em>Type</em>, see the <a href="#types">types table</a> below. For <em>Arg</em>, specify the value to be passed to the function.</p></dd>
  26. <dt>Cdecl ReturnType</dt>
  27. <dd><p id ="cdecl">The word <em>Cdecl</em> is normally omitted because most functions use the standard calling convention rather than the &quot;C&quot; calling convention (functions such as wsprintf that accept a varying number of arguments are one exception to this). If you omit Cdecl but the call yields <a href="#An">ErrorLevel A<strong>n</strong></a> -- where <strong>n</strong> is the total size of the arguments you passed -- <em>Cdecl</em> might be required. Note that most object-oriented C++ functions use the <i>thiscall</i> convention, which is not supported.</p>
  28. <p>If present, the word <em>Cdecl</em> should be listed before the return type (if any). Separate each word from the next with a space or tab. For example: <code>&quot;Cdecl Str&quot;</code>.</p>
  29. <p><span class="ver">[AHK_L 53+]:</span> Since a separate "C" calling convention does not exist in 64-bit code, <i>Cdecl</i> may be specified but has no effect on 64-bit builds of AutoHotkey.</p>
  30. <p><em>ReturnType</em>: If the function returns a 32-bit signed integer (Int), BOOL, or nothing at all, <em>ReturnType</em> may be omitted. Otherwise, specify one of the argument types from the <a href="#types">types table</a> below. The <a href="#asterisk">asterisk suffix</a> is also supported.</p></dd>
  31. </dl>
  32. <h3 id="types">Types of Arguments and Return Values</h3>
  33. <table class="info">
  34. <tr id="str">
  35. <td>Str</td>
  36. <td><p>A string such as &quot;Blue&quot; 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 <em>MyVar</em> to uppercase: <code>DllCall(&quot;CharUpper&quot;, &quot;Str&quot;, <i>MyVar</i>)</code>.</p>
  37. <p>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 <code><a href="VarSetCapacity.htm">VarSetCapacity(MyVar, 123)</a></code>, where 123 is the length that <em>MyVar</em> must be able to hold.</p>
  38. <p>A <em>Str</em> argument must not be an <a href="../Variables.htm#Expressions">expression</a> that evaluates to a number (such as i+1). If it is, the function is not called and ErrorLevel is set to -2.</p>
  39. <p>The <a href="#asterisk">asterisk variable</a> &quot;Str*&quot; is supported but rarely used. It can be used with functions that expect something like &quot;TCHAR **&quot; or &quot;LPTSTR *&quot;.</p>
  40. <p>Note: When passing a string to a function, be aware what <a href="../Compat.htm#DllCall"><i>type</i> of string</a> the function expects.</p></td>
  41. </tr>
  42. <tr>
  43. <td><span id="astr"></span><span id="wstr"></span>AStr<br>WStr</td>
  44. <td><span class="ver">[AHK_L 42+]:</span> An <b>A</b>NSI or Unicode (<b>W</b>ide character) string. See <a href="../Compat.htm#DllCall">Script Compatibility</a> for equivalent Win32 types and other details.</td>
  45. </tr>
  46. <tr>
  47. <td>Int64</td>
  48. <td>A 64-bit integer, whose range is -9223372036854775808 (-0x8000000000000000) to 9223372036854775807 (0x7FFFFFFFFFFFFFFF).</td>
  49. </tr>
  50. <tr id="Int">
  51. <td>Int</td>
  52. <td><p>A 32-bit integer (the most common integer type), whose range is -2147483648 (-0x80000000) to 2147483647 (0x7FFFFFFF). An Int is sometimes called a &quot;Long&quot;.</p>
  53. <p>An Int should also be used for each BOOL argument expected by a function (a BOOL value should be either 1 or 0).</p>
  54. <p>An <a href="#unsigned">unsigned</a> Int (UInt) is also used quite frequently, such as for DWORD.</p></td>
  55. </tr>
  56. <tr>
  57. <td>Short</td>
  58. <td>A 16-bit integer, whose range is -32768 (-0x8000) to 32767 (0x7FFF). An <a href="#unsigned">unsigned</a> Short (UShort) can be used with functions that expect a WORD.</td>
  59. </tr>
  60. <tr>
  61. <td>Char</td>
  62. <td>An 8-bit integer, whose range is -128 (-0x80) to 127 (0x7F). An <a href="#unsigned">unsigned</a> character (UChar) can be used with functions that expect a BYTE.</td>
  63. </tr>
  64. <tr>
  65. <td>Float</td>
  66. <td>A 32-bit floating point number, which provides 6 digits of precision.</td>
  67. </tr>
  68. <tr>
  69. <td>Double</td>
  70. <td>A 64-bit floating point number, which provides 15 digits of precision.</td>
  71. </tr>
  72. <tr id="ptr">
  73. <td>Ptr</td>
  74. <td><p><span class="ver">[AHK_L 42+]:</span> A <a href="../Variables.htm#PtrSize">pointer-sized</a> integer, equivalent to Int or Int64 depending on whether the exe running the script is 32-bit or 64-bit. <i>Ptr</i> 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 &quot;Ptr&quot;.</p>
  75. <p><i>Ptr</i> can also be used with the * or P suffix; it should be used with functions that output a pointer via LPVOID* or similar.</p>
  76. <p><i>UPtr</i> is also valid, but is only unsigned in 32-bit builds as AutoHotkey does not support unsigned 64-bit integers.</p>
  77. <p>If compatibility with older versions of AutoHotkey is required, use a variable type as shown below:</p>
  78. <pre>Ptr := A_PtrSize ? "Ptr" : "UInt" <em>; If A_PtrSize is not defined, use UInt instead.</em>
  79. DllCall("DeleteFile", Ptr, &amp;filename) <em>; Omit the quote marks around Ptr.</em></pre>
  80. <p>Note: To pass a <strong>NULL</strong> handle or pointer, pass the integer 0.</p></td>
  81. </tr>
  82. <tr id="asterisk">
  83. <td>* or P<br>
  84. (suffix)</td>
  85. <td><p>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: <code>DllCall(&quot;MyDll\MyFunction&quot;, &quot;Int*&quot;, MyVar)</code>.</p>
  86. <p>In general, an asterisk is used whenever a function has an argument type or return type that starts with &quot;LP&quot;. The most common example is LPDWORD, which is a pointer to a DWORD. Since a DWORD is an unsigned 32-bit integer, use &quot;UInt*&quot; or &quot;UintP&quot; 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, <a href="#str">&quot;Str&quot;</a> or &quot;Ptr&quot; should be used, depending on whether you pass a variable or its address.</p>
  87. <p>Note: &quot;Char*&quot; is not the same as <a href="#str">&quot;Str&quot;</a> because &quot;Char*&quot; passes the address of an 8-bit number, whereas <a href="#str">&quot;Str&quot;</a> passes the address of a series of characters which may be either 8-bit (ANSI) or 16-bit (Unicode), depending on the version of AutoHotkey. Similarly, &quot;UInt*&quot; 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.</p>
  88. <p>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 <a href="VarSetCapacity.htm">VarSetCapacity</a> on the variable as DllCall will update it correctly after the function returns.</p>
  89. </td>
  90. </tr>
  91. <tr id="unsigned">
  92. <td>U (prefix)</td>
  93. <td><p>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 <a href="#asterisk">asterisk variables</a> because it does not matter whether an argument passed by value is unsigned or signed (except for Int64).</p>
  94. <p>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.</p>
  95. <p><em>Unsigned</em> 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.</p></td>
  96. </tr>
  97. </TABLE>
  98. <p><strong>Note</strong>: 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, <code>Str</code> can be used in place of <code>&quot;Str&quot;</code> and <code>CDecl</code> in place of <code>&quot;CDecl&quot;</code>. In addition, the letter P may be used in place of asterisk to allow the quotes to be omitted there as well. For example: <code>UIntP</code>.</p>
  99. <h3 id="error">ErrorLevel</h3>
  100. <p><span class="ver">[v1.1.04+]</span> This function is able to throw an exception on failure. For more information, see <a href="Catch.htm#RuntimeErrors">Runtime Errors</a>.</p>
  101. <p><a href="../misc/ErrorLevel.htm">ErrorLevel</a> is set to one of the following values to indicate whether the call succeeded or failed.</p>
  102. <p><strong>0</strong>: Success.</p>
  103. <p><strong>-1</strong> (negative 1): The <em>[DllFile\]Function</em> parameter is a floating point number. A string or positive integer is required.</p>
  104. <p><strong>-2</strong>: The <a href="#types">return type</a> or one of the specified <a href="#types">arg types</a> is invalid. This error can also be caused by passing an <a href="../Variables.htm#Expressions">expression</a> that evaluates to a number to a string (<a href="#str">str</a>) argument.</p>
  105. <p><strong>-3</strong>: The specified <em>DllFile</em> could not be accessed or loaded. If no explicit path was specified for <em>DllFile</em>, the file must exist in the system's PATH or <a href="../Variables.htm#WorkingDir">A_WorkingDir</a>. This error might also occur if the user lacks permission to access the file, or if AutoHotkey is 32-bit and the DLL is 64-bit or vice versa.</p>
  106. <p><strong>-4</strong>: The specified function could not be found inside the DLL.</p>
  107. <p><strong>N</strong> (any positive number): The function was called but it aborted with fatal exception number <strong>N</strong> (for example, 0xC0000005 means &quot;access violation&quot;). In such cases, the function returns a blank value (empty string), but any <a href="#asterisk">asterisk variables</a> are still updated. An example of a fatal exception is dereferencing an invalid pointer such as NULL. Since a <a href="#cdecl">Cdecl</a> function never produces the <em>&quot;An&quot;</em> error in the next paragraph, it may generate an exception when too few arguments are passed to it.</p>
  108. <p id="An"><strong>An</strong> (the letter A followed by an integer <strong>n</strong>): The function was called but was passed too many or too few arguments. &quot;<strong>n</strong>&quot; is the number of bytes by which the argument list was incorrect. If <strong>n</strong> is positive, too many arguments (or arguments that were too large) were passed, or the call requires <a href="#cdecl">CDecl</a>. If <strong>n</strong> is negative, too few arguments were passed. This situation should be corrected to ensure reliable operation of the function. The presence of this error may also indicate that an exception occurred, in which case the function returns a blank value. Note that due to the x64 calling convention, 64-bit builds never set ErrorLevel to <b>An</b>.</p>
  109. <h3 id="except">Exceptions and A_LastError</h3>
  110. <p>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 <a href="#str">&quot;str&quot;</a> 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 <a href="#asterisk">asterisk variable</a> or <a href="#str">str</a>.</p>
  111. <p id="LastError">The built-in variable <strong>A_LastError</strong> 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 (always formatted as decimal, not hexadecimal). Like <a href="../misc/ErrorLevel.htm">ErrorLevel</a>, A_LastError is a per-thread setting; that is, interruptions by other <a href="../misc/Threads.htm">threads</a> cannot change it. However, A_LastError is also set by <a href="Run.htm#LastError">Run/RunWait</a>.</p>
  112. <h3 id="load">Performance</h3>
  113. <p>When making repeated calls to a DLL, performance can be dramatically improved by loading it explicitly (<em>this is not necessary for a <a href="#std">standard DLL</a> such as User32 because it is always resident</em>). This practice avoids the need for DllCall to internally call LoadLibrary and FreeLibrary each time. For example:</p>
  114. <pre>hModule := DllCall(&quot;<strong>LoadLibrary</strong>&quot;, &quot;Str&quot;, &quot;MyFunctions.dll&quot;, &quot;Ptr&quot;) <em>; Avoids the need for DllCall() in the loop to load the library.</em>
  115. Loop, C:\My Documents\*.*, , 1
  116. result := DllCall(&quot;MyFunctions\BackupFile&quot;, &quot;Str&quot;, A_LoopFileFullPath)
  117. DllCall(&quot;<strong>FreeLibrary</strong>&quot;, &quot;Ptr&quot;, hModule) <em>; To conserve memory, the DLL may be unloaded after using it.</em></pre>
  118. <p>In v1.0.46.08+, even faster performance can be achieved by looking up the function's address beforehand. For example:</p>
  119. <pre><em>; In the following example, if the DLL isn't yet loaded, use LoadLibrary in place of GetModuleHandle.</em>
  120. <strong>MulDivProc</strong> := DllCall(&quot;GetProcAddress&quot;, Ptr, DllCall(&quot;GetModuleHandle&quot;, Str, &quot;<strong>kernel32</strong>&quot;, &quot;Ptr&quot;), AStr, &quot;<strong>MulDiv</strong>&quot;, &quot;Ptr&quot;)
  121. Loop 500
  122. DllCall(<strong>MulDivProc</strong>, Int, 3, Int, 4, Int, 3)</pre>
  123. <p><span class="ver">[AHK_L 31+]:</span> If DllCall's first parameter is a literal string such as <code>"MulDiv"</code> 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.</p>
  124. <p>Also, adding the line <a href="_NoEnv.htm">#NoEnv</a> anywhere in the script improves DllCall's performance when unquoted parameter types are used (e.g. Int vs. &quot;Int&quot;).</p>
  125. <p>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 <a href="../Variables.htm#amp">by address</a> (e.g. &amp;MyVar) rather than as a &quot;<a href="#str">str</a>&quot; (especially when the string is very long). The following example converts a string to uppercase: <code>DllCall(&quot;CharUpper&quot;, <strong>Ptr</strong>, <strong>&amp;</strong>MyVar, Ptr)</code>.</p>
  126. <h3 id="struct">Structures and Arrays</h3>
  127. <p>A structure is a collection of <em>members</em> (fields) stored adjacently in memory. Most members tend to be integers.</p>
  128. <p>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:</p>
  129. <p>1) Call <code><a href="VarSetCapacity.htm">VarSetCapacity</a>(MyStruct, 123, 0)</code> 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.</p>
  130. <p>2) If the target function uses the values initially in the structure, call <code><a href="NumPut.htm">NumPut</a>(123, MyStruct, 4, "UInt")</code> to initialize any members that should be non-zero. Replace 123 with the integer to be put into the target member (or specify <code>&amp;Var</code> to store the <a href="../Variables.htm#amp">address</a> of a variable). Replace 4 with the offset of the target member (see step #4 for description of &quot;offset&quot;). Replace "UInt" with the appropriate type or omit it if the member is a pointer or handle.</p>
  131. <p>3) Call the target function, passing the <a href="../Variables.htm#amp">address</a> of MyStruct as a UInt (or Ptr in AHK_L 42+) argument. For example, <code>DllCall(&quot;MyDll\MyFunc&quot;, Ptr, <strong>&amp;</strong>MyStruct)</code>. The function will examine and/or change some of the members.</p>
  132. <p>4) Use <code>MyInteger := <a href="NumGet.htm">NumGet</a>(MyStruct, 4, "UInt")</code> 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 <a href="#Int">other types of 32-bit integers</a> -- are 4 bytes in size. Replace "UInt" with the appropriate type or omit it if the member is a pointer or handle.</p>
  133. <p>See <a href="#ExStruct">Structure Examples</a> for actual usages.</p>
  134. <h3 id="limits">Known Limitations</h3>
  135. <p>When a <a href="../Variables.htm#amp">variable's address</a> (e.g. <code>&amp;MyVar</code>) 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 <a href="#str">&quot;Str&quot;</a> argument rather than as a Ptr/address; 2) In v1.0.44.03+, call <code><a href="VarSetCapacity.htm#neg1">VarSetCapacity(MyVar, -1)</a></code> to update the variable's internally-stored length after calling DllCall.</p>
  136. <p>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 commands and functions. However, such data can be manipulated by the <a href="../Variables.htm#amp">address operator</a> and <a href="NumPut.htm">NumPut</a>/<a href="NumGet.htm">NumGet</a>, as well as DllCall itself.</p>
  137. <p>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 <code>CharLower(CharUpper(MyVar))</code> in a programming language would convert <em>MyVar</em>'s contents to lowercase. But when the same is done with DllCall(), <em>MyVar</em> would be uppercase after the following call because CharLower would have operated on a different/temporary string whose contents were identical to <em>MyVar</em>:</p>
  138. <pre>MyVar = ABC
  139. result := DllCall(&quot;CharLower&quot;, <strong><u>str</u></strong>, DllCall(&quot;CharUpper&quot;, Str, MyVar, <strong><u>Str</u></strong>), Str)</pre>
  140. <p>To work around this, change the two underlined &quot;Str&quot; values above to Ptr. This interprets CharUpper's return value as a pure address that will get passed as an integer to CharLower.</p>
  141. <p>Certain limitations may be encountered when dealing with strings. For details, see <a href="../Compat.htm#DllCall">Script Compatibility</a>.</p>
  142. <h3 id="COM">Component Object Model (COM)</h3>
  143. <p>COM objects which are accessible to VBScript and similar languages are typically also accessible to AutoHotkey via <a href="ComObjCreate.htm">ComObjCreate</a>, <a href="ComObjGet.htm">ComObjGet</a> or <a href="ComObjActive.htm">ComObjActive</a> and the built-in <a href="../Objects.htm#Usage_Objects">object syntax</a>.</p>
  144. <p>COM objects which don't support <a href="http://msdn.microsoft.com/en-us/library/ms221608.aspx">IDispatch</a> 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 <a href="#ExTaskbar">the example</a> further below.</p>
  145. <p>Much of the .NET Framework is also accessible via COM and DllCall. See <a href="http://www.autohotkey.com/forum/topic26191.html">http://www.autohotkey.com/forum/topic26191.html</a>.
  146. </p>
  147. <h3>Related</h3>
  148. <p><a href="../Compat.htm#DllCall">Script Compatibility</a>, <a href="PostMessage.htm">PostMessage</a>, <a href="OnMessage.htm">OnMessage()</a>, <a href="RegisterCallback.htm">RegisterCallback()</a>, <a href="Run.htm">Run</a>, <a href="VarSetCapacity.htm">VarSetCapacity</a>, <a href="../Functions.htm">Functions</a>, <a href="SysGet.htm">SysGet</a>, <a href="http://msdn.microsoft.com/library/">MSDN Library</a></p>
  149. <h3>Examples</h3>
  150. <pre class="NoIndent"><em>; Example: Calls the Windows API function &quot;MessageBox&quot; and report which button the user presses.</em>
  151. WhichButton := DllCall(&quot;MessageBox&quot;, &quot;Int&quot;, &quot;0&quot;, &quot;Str&quot;, &quot;Press Yes or No&quot;, &quot;Str&quot;, &quot;Title of box&quot;, &quot;Int&quot;, 4)
  152. MsgBox You pressed button #%WhichButton%.</pre>
  153. <pre class="NoIndent"><em>; Example: Changes the desktop wallpaper to the specified bitmap (.bmp) file.</em>
  154. DllCall(&quot;SystemParametersInfo&quot;, UInt, 0x14, UInt, 0, Str, <i>A_WinDir <strong>.</strong> &quot;\winnt.bmp&quot;</i>, UInt, 2)</pre>
  155. <pre class="NoIndent"><em>; Example: Calls the API function &quot;IsWindowVisible&quot; to find out if a Notepad window is visible.</em>
  156. DetectHiddenWindows On
  157. if not DllCall(&quot;IsWindowVisible&quot;, &quot;Ptr&quot;, WinExist(&quot;Untitled - Notepad&quot;)) <em>; WinExist() returns an HWND.</em>
  158. MsgBox The window is not visible.</pre>
  159. <pre class="NoIndent"><em>; Example: Calls the API's wsprintf() to pad the number 432 with leading zeros to make it 10 characters wide (0000000432).</em>
  160. VarSetCapacity(ZeroPaddedNumber, 20) <em>; Ensure the variable is large enough to accept the new string.</em>
  161. DllCall(&quot;wsprintf&quot;, &quot;Str&quot;, ZeroPaddedNumber, &quot;Str&quot;, &quot;%010d&quot;, &quot;Int&quot;, 432, &quot;Cdecl&quot;) <em>; Requires the Cdecl calling convention.</em>
  162. MsgBox %ZeroPaddedNumber%</pre>
  163. <pre class="NoIndent" id="QPC"><em>; Example: Demonstrates QueryPerformanceCounter(), which gives more precision than <a href="../Variables.htm#TickCount">A_TickCount's</a> 10ms.</em>
  164. DllCall(&quot;QueryPerformanceCounter&quot;, &quot;Int64*&quot;, CounterBefore)
  165. Sleep 1000
  166. DllCall(&quot;QueryPerformanceCounter&quot;, &quot;Int64*&quot;, CounterAfter)
  167. MsgBox % &quot;Elapsed QPC time is &quot; . CounterAfter - CounterBefore</pre>
  168. <pre class="NoIndent"><em>; Example: This is a hotkey that temporarily reduces the mouse cursor's speed, which facilitates precise positioning.
  169. ; Hold down the F1 key to slow down the cursor. Release it to return to original speed.</em>
  170. F1::
  171. SPI_GETMOUSESPEED = 0x70
  172. SPI_SETMOUSESPEED = 0x71
  173. <em>; Retrieve the current speed so that it can be restored later:</em>
  174. <strong>DllCall</strong>(&quot;SystemParametersInfo&quot;, UInt, SPI_GETMOUSESPEED, UInt, 0, UIntP, OrigMouseSpeed, UInt, 0)
  175. <em>; Now set the mouse to the slower speed specified in the next-to-last parameter (the range is 1-20, 10 is default):</em>
  176. <strong>DllCall</strong>(&quot;SystemParametersInfo&quot;, UInt, SPI_SETMOUSESPEED, UInt, 0, Ptr, <strong>3</strong>, UInt, 0)
  177. KeyWait F1 <em>; This prevents keyboard auto-repeat from doing the DllCall repeatedly.</em>
  178. return
  179. F1 up::<strong>DllCall</strong>(&quot;SystemParametersInfo&quot;, UInt, 0x71, UInt, 0, Ptr, OrigMouseSpeed, UInt, 0) <em>; Restore the original speed.</em></pre>
  180. <pre class="NoIndent" id="GetChildHWND"><em>; Example: When passed a window's Unique ID and the text or ClassNN of one of its controls,
  181. ; the following function returns the HWND (unique ID) of that control.
  182. ; v1.0.43.06+: This function has been superseded by the following command, which is more accurate.</em>
  183. <a href="ControlGet.htm#Hwnd">ControlGet, OutputVar, Hwnd,, ClassNN, WinTitle</a></pre>
  184. <pre class="NoIndent"><em>; Example: Monitors the active window and display the position of its vertical scroll bar in its
  185. ; focused control (with real-time updates). This requires v1.0.43.06+ because it uses <a href="ControlGet.htm#Hwnd">ControlGet Hwnd</a>.</em>
  186. #Persistent
  187. SetTimer, WatchScrollBar, 100
  188. return
  189. WatchScrollBar:
  190. ActiveWindow := WinExist(&quot;A&quot;)
  191. if not ActiveWindow <em>; No active window.</em>
  192. return
  193. ControlGetFocus, FocusedControl, ahk_id %ActiveWindow%
  194. if not FocusedControl <em>; No focused control.</em>
  195. return
  196. <em>; Display the vertical or horizontal scroll bar's position in a ToolTip:</em>
  197. ControlGet, ChildHWND, Hwnd,, %FocusedControl%, ahk_id %ActiveWindow%
  198. ToolTip % <strong>DllCall</strong>(&quot;GetScrollPos&quot;, &quot;Ptr&quot;, ChildHWND, &quot;Int&quot;, 1) <em>; Last parameter is 1 for SB_VERT, 0 for SB_HORZ.</em>
  199. return</pre>
  200. <pre class="NoIndent" id="file"><em>; Example: This is a working script that writes some text to a file then reads it back into memory (requires v1.0.34+).
  201. ; This method can be used to help performance in cases where multiple files are being read or written simultaneously.
  202. ; in AHK_L 42+, <a href="FileOpen.htm#writeread">the same can be achieved</a> using <a href="FileOpen.htm">FileOpen</a>.</em>
  203. FileSelectFile, FileName, S16,, Create a new file:
  204. if FileName =
  205. return
  206. GENERIC_WRITE = 0x40000000 <em>; Open the file for writing rather than reading.</em>
  207. CREATE_ALWAYS = 2 <em>; Create new file (overwriting any existing file).</em>
  208. hFile := <strong>DllCall</strong>(&quot;CreateFile&quot;, Str, FileName, UInt, GENERIC_WRITE, UInt, 0, Ptr, 0, UInt, CREATE_ALWAYS, UInt, 0, Ptr, 0, Ptr)
  209. if not hFile
  210. {
  211. MsgBox Can't open &quot;%FileName%&quot; for writing.
  212. return
  213. }
  214. TestString = This is a test string.`r`n <em>; When writing a file this way, use `r`n rather than `n to start a new line.</em>
  215. <strong>DllCall</strong>(&quot;WriteFile&quot;, Ptr, hFile, Str, TestString, UInt, StrLen(TestString), UIntP, BytesActuallyWritten, Ptr, 0)
  216. <strong>DllCall</strong>(&quot;CloseHandle&quot;, Ptr, hFile) <em>; Close the file.</em>
  217. <em>; Now that the file was written, read its contents back into memory.</em>
  218. GENERIC_READ = 0x80000000 <em>; Open the file for reading rather than writing.</em>
  219. OPEN_EXISTING = 3 <em>; This mode indicates that the file to be opened must already exist.</em>
  220. FILE_SHARE_READ = 0x1 <em>; This and the next are whether other processes can open the file while we have it open.</em>
  221. FILE_SHARE_WRITE = 0x2
  222. hFile := <strong>DllCall</strong>(&quot;CreateFile&quot;, Str, FileName, UInt, GENERIC_READ, UInt, FILE_SHARE_READ|FILE_SHARE_WRITE, Ptr, 0, UInt, OPEN_EXISTING, UInt, 0, Ptr, 0)
  223. if not hFile
  224. {
  225. MsgBox Can't open &quot;%FileName%&quot; for reading.
  226. return
  227. }
  228. <em>; Make the variable empty for testing purposes, but ensure it retains sufficient capacity:</em>
  229. BytesToRead := VarSetCapacity(TestString, StrLen(TestString))
  230. <strong>DllCall</strong>(&quot;ReadFile&quot;, Ptr, hFile, Str, TestString, UInt, BytesToRead, UIntP, BytesActuallyRead, Ptr, 0)
  231. <strong>DllCall</strong>(&quot;CloseHandle&quot;, Ptr, hFile) <em>; Close the file.</em>
  232. MsgBox The following string was read from the file: %TestString%</pre>
  233. <pre class="NoIndent" id="HideCursor"><em>; Example: Hides the mouse cursor when you press Win+C. To later show the cursor, press Win+C again.
  234. ; This script is from <a href="http://www.autohotkey.com/forum/topic6107.html">www.autohotkey.com/forum/topic6107.html</a></em>
  235. OnExit, ShowCursor <em>; Ensure the cursor is made visible when the script exits.</em>
  236. return
  237. ShowCursor:
  238. SystemCursor(&quot;On&quot;)
  239. ExitApp
  240. #c::SystemCursor(&quot;Toggle&quot;) <em>; Win+C hotkey to toggle the cursor on and off.</em>
  241. SystemCursor(OnOff=1) <em>; INIT = &quot;I&quot;,&quot;Init&quot;; OFF = 0,&quot;Off&quot;; TOGGLE = -1,&quot;T&quot;,&quot;Toggle&quot;; ON = others</em>
  242. {
  243. static AndMask, XorMask, $, h_cursor
  244. ,c0,c1,c2,c3,c4,c5,c6,c7,c8,c9,c10,c11,c12,c13 <em>; system cursors</em>
  245. , b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13 <em>; blank cursors</em>
  246. , h1,h2,h3,h4,h5,h6,h7,h8,h9,h10,h11,h12,h13 <em>; handles of default cursors</em>
  247. if (OnOff = &quot;Init&quot; or OnOff = &quot;I&quot; or $ = &quot;&quot;) <em>; init when requested or at first call</em>
  248. {
  249. $ = h <em>; active default cursors</em>
  250. VarSetCapacity( h_cursor,4444, 1 )
  251. VarSetCapacity( AndMask, 32*4, 0xFF )
  252. VarSetCapacity( XorMask, 32*4, 0 )
  253. system_cursors = 32512,32513,32514,32515,32516,32642,32643,32644,32645,32646,32648,32649,32650
  254. StringSplit c, system_cursors, `,
  255. Loop %c0%
  256. {
  257. h_cursor := DllCall( &quot;LoadCursor&quot;, &quot;Ptr&quot;,0, &quot;Ptr&quot;,c%A_Index% )
  258. h%A_Index% := DllCall( &quot;CopyImage&quot;, &quot;Ptr&quot;,h_cursor, &quot;UInt&quot;,2, &quot;Int&quot;,0, &quot;Int&quot;,0, &quot;UInt&quot;,0 )
  259. b%A_Index% := DllCall( &quot;CreateCursor&quot;, &quot;Ptr&quot;,0, &quot;Int&quot;,0, &quot;Int&quot;,0
  260. , &quot;Int&quot;,32, &quot;Int&quot;,32, &quot;Ptr&quot;,&amp;AndMask, &quot;Ptr&quot;,&amp;XorMask )
  261. }
  262. }
  263. if (OnOff = 0 or OnOff = &quot;Off&quot; or $ = &quot;h&quot; and (OnOff &lt; 0 or OnOff = &quot;Toggle&quot; or OnOff = &quot;T&quot;))
  264. $ = b <em>; use blank cursors</em>
  265. else
  266. $ = h <em>; use the saved cursors</em>
  267. Loop %c0%
  268. {
  269. h_cursor := DllCall( &quot;CopyImage&quot;, &quot;Ptr&quot;,%$%%A_Index%, &quot;UInt&quot;,2, &quot;Int&quot;,0, &quot;Int&quot;,0, &quot;UInt&quot;,0 )
  270. DllCall( &quot;SetSystemCursor&quot;, &quot;Ptr&quot;,h_cursor, &quot;UInt&quot;,c%A_Index% )
  271. }
  272. }</pre>
  273. <pre class="NoIndent" id="ExStruct"><em>; Structure Example: Pass the address of a RECT structure to GetWindowRect(), which sets the structure's
  274. ; members to the positions of the left, top, right, and bottom sides of a window (relative to the screen).</em>
  275. Run Notepad
  276. WinWait Untitled - Notepad <em>; This also sets the &quot;<a href="../misc/WinTitle.htm#LastFoundWindow">last found window</a>&quot; for use with WinExist() below.</em>
  277. VarSetCapacity(Rect, 16) <em>; A RECT is a struct consisting of four 32-bit integers (i.e. 4*4=16).</em>
  278. <strong>DllCall</strong>(&quot;GetWindowRect&quot;, Ptr, WinExist(), Ptr, &amp;Rect) <em>; WinExist() returns an HWND.</em>
  279. MsgBox % &quot;Left &quot; . <a href="NumGet.htm">NumGet</a>(Rect, 0, "Int") . &quot; Top &quot; . NumGet(Rect, 4, "Int")
  280. . &quot; Right &quot; . NumGet(Rect, 8, "Int") . &quot; Bottom &quot; . NumGet(Rect, 12, "Int")</pre>
  281. <pre class="NoIndent"><em>; Structure Example: Pass to FillRect() the address of a RECT structure that indicates a part of the
  282. ; screen to temporarily paint red.</em>
  283. VarSetCapacity(Rect, 16, 0) <em>; Set capacity to hold four 4-byte integers and initialize them all to zero.</em>
  284. <a href="NumPut.htm">NumPut</a>(A_ScreenWidth//2, Rect, 8, "Int") <em>; The third integer in the structure is &quot;rect.right&quot;.</em>
  285. NumPut(A_ScreenHeight//2, Rect, 12, "Int") <em>; The fourth integer in the structure is &quot;rect.bottom&quot;.</em>
  286. hDC := <strong>DllCall</strong>(&quot;GetDC&quot;, "Ptr", 0, "Ptr") <em>; Pass zero to get the desktop's device context.</em>
  287. hBrush := <strong>DllCall</strong>(&quot;CreateSolidBrush&quot;, "UInt", 0x0000FF, "Ptr") <em>; Create a red brush (0x0000FF is in BGR format).</em>
  288. <strong>DllCall</strong>(&quot;FillRect&quot;, "Ptr", hDC, "Ptr", &amp;Rect, "Ptr", hBrush) <em>; Fill the specified rectangle using the brush above.</em>
  289. <strong>DllCall</strong>(&quot;ReleaseDC&quot;, "Ptr", 0, "Ptr", hDC) <em>; Clean-up.</em>
  290. <strong>DllCall</strong>(&quot;DeleteObject&quot;, "Ptr", hBrush) <em>; Clean-up.</em></pre>
  291. <pre class="NoIndent"><em>; Structure Example: Change the system's clock to the specified date and time. Use caution when
  292. ; changing to a date in the future as it may cause scheduled tasks to run prematurely!</em>
  293. SetSystemTime(&quot;20051008142211&quot;) <em>; Pass it a <a href="FileSetTime.htm#YYYYMMDD">timestamp</a> (local, not UTC).</em>
  294. SetSystemTime(YYYYMMDDHHMISS)
  295. <em>; Sets the system clock to the specified date and time.
  296. ; Caller must ensure that the incoming parameter is a valid date-time stamp
  297. ; (local time, not UTC). Returns non-zero upon success and zero otherwise.</em>
  298. {
  299. <em>; Convert the parameter from local time to UTC for use with SetSystemTime().</em>
  300. UTC_Delta -= A_NowUTC, Seconds <em>; Seconds is more accurate due to rounding issue.</em>
  301. UTC_Delta := Round(-UTC_Delta/60) <em>; Round to nearest minute to ensure accuracy.</em>
  302. YYYYMMDDHHMISS += UTC_Delta, Minutes <em>; Apply offset to convert to UTC.</em>
  303. VarSetCapacity(SystemTime, 16, 0) <em>; This struct consists of 8 UShorts (i.e. 8*2=16).</em>
  304. StringLeft, Int, YYYYMMDDHHMISS, 4 <em>; YYYY (year)</em>
  305. <a href="NumPut.htm">NumPut</a>(Int, SystemTime, 0, &quot;UShort&quot;)
  306. StringMid, Int, YYYYMMDDHHMISS, 5, 2 <em>; MM (month of year, 1-12)</em>
  307. NumPut(Int, SystemTime, 2, &quot;UShort&quot;)
  308. StringMid, Int, YYYYMMDDHHMISS, 7, 2 <em>; DD (day of month)</em>
  309. NumPut(Int, SystemTime, 6, &quot;UShort&quot;)
  310. StringMid, Int, YYYYMMDDHHMISS, 9, 2 <em>; HH (hour in 24-hour time)</em>
  311. NumPut(Int, SystemTime, 8, &quot;UShort&quot;)
  312. StringMid, Int, YYYYMMDDHHMISS, 11, 2 <em>; MI (minute)</em>
  313. NumPut(Int, SystemTime, 10, &quot;UShort&quot;)
  314. StringMid, Int, YYYYMMDDHHMISS, 13, 2 <em>; SS (second)</em>
  315. NumPut(Int, SystemTime, 12, &quot;UShort&quot;)
  316. return <strong>DllCall</strong>(&quot;SetSystemTime&quot;, Ptr, &amp;SystemTime)
  317. }</pre>
  318. <pre class="NoIndent"><em>/* <strong>More Structure Examples:</strong>
  319. 1) See the <a href="../scripts/WinLIRC.htm">WinLIRC client script</a> for a demonstration of how to use DllCall() to make a network connection
  320. to a TCP/IP server and receive data from it.
  321. 2) The operating system offers standard dialog boxes that prompt the user to pick a font and/or color, or an icon.
  322. These dialogs use structures and are demonstrated at <a href="http://www.autohotkey.com/forum/topic17230.html">www.autohotkey.com/forum/topic17230.html</a>.
  323. */</em></pre>
  324. <pre id="ExTaskbar" class="NoIndent"><em>/*
  325. Example: Temporarily remove the active window from the taskbar by using COM.
  326. Methods in <a href="http://msdn.microsoft.com/en-us/library/bb774652.aspx">ITaskbarList</a>'s VTable:
  327. IUnknown:
  328. 0 QueryInterface -- use <a href="ComObjQuery.htm">ComObjQuery</a> instead
  329. 1 AddRef -- use <a href="ObjAddRef.htm">ObjAddRef</a> instead
  330. 2 Release -- use <a href="ObjAddRef.htm">ObjRelease</a> instead
  331. ITaskbarList:
  332. 3 HrInit
  333. 4 AddTab
  334. 5 DeleteTab
  335. 6 ActivateTab
  336. 7 SetActiveAlt
  337. */</em>
  338. IID_ITaskbarList := "{56FDF342-FD6D-11d0-958A-006097C9A090}"
  339. CLSID_TaskbarList := "{56FDF344-FD6D-11d0-958A-006097C9A090}"
  340. <em>; Create the TaskbarList object and store its address in tbl.</em>
  341. tbl := <a href="ComObjCreate.htm">ComObjCreate</a>(CLSID_TaskbarList, IID_ITaskbarList)
  342. activeHwnd := WinExist("A")
  343. DllCall(vtable(tbl,3), "ptr", tbl) <em>; tbl.<a href="http://msdn.microsoft.com/en-us/library/bb774650.aspx">HrInit</a>()</em>
  344. DllCall(vtable(tbl,5), "ptr", tbl, "ptr", activeHwnd) <em>; tbl.<a href="http://msdn.microsoft.com/en-us/library/bb774648.aspx">DeleteTab</a>(activeHwnd)</em>
  345. Sleep 3000
  346. DllCall(vtable(tbl,4), "ptr", tbl, "ptr", activeHwnd) <em>; tbl.<a href="http://msdn.microsoft.com/en-us/library/bb774646.aspx">AddTab</a>(activeHwnd)</em>
  347. <em>; Non-dispatch objects must always be manually freed.</em>
  348. ObjRelease(tbl)
  349. vtable(ptr, n) {
  350. <em>; NumGet(ptr+0) returns the address of the object's virtual function
  351. ; table (vtable for short). The remainder of the expression retrieves
  352. ; the address of the nth function's address from the vtable.</em>
  353. return NumGet(NumGet(ptr+0), n*A_PtrSize)
  354. }
  355. </pre>
  356. </body>
  357. </html>