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

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

https://gitlab.com/ahkscript/Autohotkey.docset
HTML | 160 lines | 128 code | 32 blank | 0 comment | 0 complexity | 0844bbec8655411ac75ae69384974f2a MD5 | raw file
  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <title>RegisterCallback</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>RegisterCallback() <span class="ver">[v1.0.47+]</span></h1>
  12. <p>Creates a machine-code address that when called, redirects the call to a <a href="../Functions.htm">function</a> in the script.</p>
  13. <pre class="Syntax">Address := RegisterCallback(&quot;FunctionName&quot; [, Options = &quot;&quot;, ParamCount = FormalCount, EventInfo = Address])</pre>
  14. <h3>Parameters</h3>
  15. <dl>
  16. <dt>Address</dt>
  17. <dd><p>Upon success, RegisterCallback() returns a numeric address that may be called by <a href="DllCall.htm">DllCall()</a> or anything else capable of calling a machine-code function. Upon failure, it returns an empty string. Failure occurs when <em>FunctionName</em>: 1) does not exist; 2) accepts too many or too few parameters according to <em>ParamCount</em>; or 3) accepts any <a href="../Functions.htm#ByRef">ByRef parameters</a>.</p></dd>
  18. <dt>FunctionName</dt>
  19. <dd>
  20. <p>A <a href="../Functions.htm">function</a>'s name, which must be enclosed in quotes if it is a literal string. This function is called automatically whenever <em>Address</em> is called. The function also receives the parameters that were passed to <em>Address</em>.</p>
  21. <p><span class="ver">[v1.1.06+]:</span> A <a href="../objects/Func.htm">function reference</a> can be passed instead of a function name.</p>
  22. </dd>
  23. <dt>Options</dt>
  24. <dd><p>Specify zero or more of the following words. Separate each option from the next with a space (e.g. <code>C Fast</code>).</p>
  25. <p id="Fast"><strong>Fast</strong> or <strong>F</strong>: Avoids starting a new <a href="../misc/Threads.htm">thread</a> each time <em>FunctionName</em> is called. Although this performs better, it must be avoided whenever the thread from which <em>Address</em> is called varies (e.g. when the callback is triggered by an incoming message). This is because <em>FunctionName</em> will be able to change global settings such as <a href="../misc/ErrorLevel.htm">ErrorLevel</a>, <a href="../Variables.htm#LastError">A_LastError</a>, and the <a href="../misc/WinTitle.htm#LastFoundWindow">last-found window</a> for whichever thread happens to be running at the time it is called. For more information, see <a href="#Threads">Remarks</a>.</p>
  26. <p><strong>CDecl</strong> or <strong>C</strong>: Makes <em>Address</em> conform to the &quot;C&quot; calling convention. This is typically omitted because the standard calling convention is much more common for callbacks.</p></dd>
  27. <dt>ParamCount</dt>
  28. <dd><p>The number of parameters that <em>Address</em>'s caller will pass to it. If entirely omitted, it defaults to the number of mandatory parameters in the <a href="../Functions.htm#define">definition</a> of <em>FunctionName</em>. In either case, ensure that the caller passes exactly this number of parameters.</p></dd>
  29. <dt>EventInfo</dt>
  30. <dd>
  31. <p>An integer that <em>FunctionName</em> will see in <a href="../Variables.htm#EventInfo">A_EventInfo</a> whenever it is called via this <em>Address</em>. This is useful when <em>FunctionName</em> is called by more than one <em>Address</em>. If omitted, it defaults to <em>Address</em>. Note: Unlike other global settings, the <a href="../misc/Threads.htm">current thread</a>'s A_EventInfo is not disturbed by the <a href="#Fast">fast mode</a>.</p>
  32. <p>If the exe running the script is 32-bit, this parameter must be between 0 and 4294967295. If the exe is 64-bit, this parameter can be a 64-bit integer. Although <a href="../Variables.htm#EventInfo">A_EventInfo</a> usually returns an unsigned integer, AutoHotkey does not fully support unsigned 64-bit integers and therefore some operations may cause the value to wrap into the signed range.</p></dd>
  33. </dl>
  34. <h3>The Callback Function's Parameters</h3>
  35. <p>A <a href="../Functions.htm">function</a> assigned to a callback address may accept up to 31 parameters. <a href="../Functions.htm#optional">Optional parameters</a> are permitted, which is useful when the function is called by more than one caller.</p>
  36. <p>Interpreting the parameters correctly requires some understanding of how the x86 calling conventions work. Since AutoHotkey does not have typed parameters, the callback's parameter list is assumed to consist of integers, and some reinterpretation may be required.</p>
  37. <p><strong>AutoHotkey 32-bit:</strong> All incoming parameters are unsigned 32-bit integers. Smaller types are padded out to 32 bits, while larger types are split into a series of 32-bit parameters.</p>
  38. <p>If an incoming parameter is intended to be a signed integer, any negative numbers can be revealed by following either of the following examples:</p>
  39. <pre><em>; Method #1</em>
  40. if wParam > 0x7FFFFFFF
  41. wParam := -(~wParam) - 1
  42. <em>; Method #2: Relies on the fact that AutoHotkey natively uses signed 64-bit integers.</em>
  43. wParam := wParam &lt;&lt; 32 &gt;&gt; 32</pre>
  44. <p><strong>AutoHotkey 64-bit:</strong> All incoming parameters are signed 64-bit integers. AutoHotkey does not natively support unsigned 64-bit integers. Smaller types are padded out to 64 bits, while larger types are always passed by address.</p>
  45. <p><strong>AutoHotkey 32-bit/64-bit:</strong> If an incoming parameter is intended to be 8-bit or 16-bit (or 32-bit on x64), the upper bits of the value might contain "garbage" which can be filtered out by using bitwise-and, as in the following examples:</p>
  46. <pre>Callback(UCharParam, UShortParam, UIntParam) {
  47. UCharParam &amp;= 0xFF
  48. UShortParam &amp;= 0xFFFF
  49. UIntParam &amp;= 0xFFFFFFFF
  50. <em>;...</em>
  51. }</pre>
  52. <p>If an incoming parameter is intended by its caller to be a string, what it actually receives is the address of the string. To retrieve the string itself, use <a href="StrPutGet.htm">StrGet</a>:</p>
  53. <pre>MyString := StrGet(MyParameter) <em>; AHK_L 46+</em></pre>
  54. <p>If an incoming parameter is the address of a structure, the individual members may be extracted by following the steps at <a href="DllCall.htm#struct">DllCall structures</a>.</p>
  55. <p id="Indirect"><strong>Receiving parameters by address</strong> <span class="ver">[AHK_L 60+]</span>: If the function is declared as <a href="../Functions.htm#Variadic">variadic</a>, its final parameter is assigned the <i>address</i> of the first callback parameter which was not assigned to a script parameter. For example:</p>
  56. <pre>
  57. callback := RegisterCallback("TheFunc", "F", 1) <em>; Parameter count must be specified.</em>
  58. TheFunc("TheFunc was called directly.") <em>; Call TheFunc directly.</em>
  59. DllCall(callback, float, 10.5, int64, 42) <em>; Call TheFunc via callback.</em>
  60. TheFunc(params*) {
  61. if IsObject(params)
  62. MsgBox % params[1]
  63. else
  64. MsgBox % <a href="NumGet.htm">NumGet</a>(params+0, "float") ", " NumGet(params+A_PtrSize, "int64")
  65. }</pre>
  66. <p>Most callbacks use the <i>stdcall</i> calling convention, which requires a fixed number of parameters. In those cases, <i>ParamCount</i> must be specified when the callback is created. <i>ParamCount</i> may be omitted on 64-bit builds and for <i>Cdecl</i> callbacks on 32-bit builds - in such cases all optional parameters receive their default values and are ignored for the purpose of calculating the address to store in <i>params</i>.</p>
  67. <h3>What the Function Should <em>Return</em></h3>
  68. <p>If the function uses <a href="Return.htm">Return</a> without any parameters, or it specifies a blank value such as &quot;&quot; (or it never uses Return at all), 0 is returned to the caller of the callback. Otherwise, the function should return an integer, which is then returned to the caller. AutoHotkey 32-bit truncates return values to 32-bit, while AutoHotkey 64-bit supports 64-bit return values. Returning structs larger than this (by value) is not supported.</p>
  69. <h3 id="Threads">Fast vs. Slow</h3>
  70. <p>The default/slow mode causes the function to start off fresh with the default values for settings such as <a href="SendMode.htm">SendMode</a> and <a href="DetectHiddenWindows.htm">DetectHiddenWindows</a>. These defaults can be changed in the <a href="../Scripts.htm#auto">auto-execute section</a>.</p>
  71. <p>By contrast, the <a href="#Fast">fast mode</a> inherits global settings from whichever <a href="../misc/Threads.htm">thread</a> happens to be running at the time the function is called. Furthermore, any changes the function makes to global settings (including <a href="../misc/ErrorLevel.htm">ErrorLevel</a> and the <a href="../misc/WinTitle.htm#LastFoundWindow">last-found window</a>) will go into effect for the <a href="../misc/Threads.htm">current thread</a>. Consequently, the fast mode should be used only when it is known exactly which thread(s) the function will be called from.</p>
  72. <p>To avoid being interrupted by itself (or any other thread), a callback may use <a href="Critical.htm">Critical</a> as its first line. However, this is not completely effective when the function is called indirectly via the arrival of a message less than 0x312 (increasing Critical's <a href="Critical.htm#Interval">interval</a> may help). Furthermore, <a href="Critical.htm">Critical</a> does not prevent the function from doing something that might indirectly result in a call to itself, such as calling <a href="PostMessage.htm">SendMessage</a> or <a href="DllCall.htm">DllCall</a>.</p>
  73. <h3>Memory</h3>
  74. <p>Each use of RegisterCallback() allocates a small amount of memory (32 bytes plus system overhead). Since the OS frees this memory automatically when the script exits, any script that allocates a small, <em>fixed</em> number of callbacks does not have to explicitly free the memory. By contrast, a script that calls RegisterCallback() an indefinite/unlimited number of times should explicitly call the following on any unused callbacks:</p>
  75. <pre>DllCall(&quot;GlobalFree&quot;, &quot;Ptr&quot;, Address, &quot;Ptr&quot;)</pre>
  76. <h3>Related</h3>
  77. <p><a href="DllCall.htm">DllCall()</a>, <a href="OnMessage.htm">OnMessage()</a>, <a href="OnExit.htm">OnExit</a>, <a href="OnClipboardChange.htm">OnClipboardChange</a>, <a href="Sort.htm#callback">Sort's callback</a>, <a href="Critical.htm">Critical</a>, <a href="PostMessage.htm">Post/SendMessage</a>, <a href="../Functions.htm">Functions</a>, <a href="../misc/SendMessageList.htm">List of Windows Messages</a>, <a href="../misc/Threads.htm">Threads</a></p>
  78. <h3>Examples</h3>
  79. <pre class="NoIndent"><em>; Example: The following is a working script that displays a summary of all top-level windows.</em>
  80. <em>; For performance and memory conservation, call RegisterCallback() only once for a given callback:</em>
  81. if not EnumAddress <em>; Fast-mode is okay because it will be called only from this thread:</em>
  82. EnumAddress := <strong>RegisterCallback</strong>(&quot;EnumWindowsProc&quot;, &quot;Fast&quot;)
  83. DetectHiddenWindows On <em>; Due to fast-mode, this setting will go into effect for the callback too.</em>
  84. <em>; Pass control to EnumWindows(), which calls the callback repeatedly:</em>
  85. DllCall(&quot;EnumWindows&quot;, Ptr, EnumAddress, Ptr, 0)
  86. MsgBox %Output% <em>; Display the information accumulated by the callback.</em>
  87. EnumWindowsProc(hwnd, lParam)
  88. {
  89. global Output
  90. WinGetTitle, title, ahk_id %hwnd%
  91. WinGetClass, class, ahk_id %hwnd%
  92. if title
  93. Output .= &quot;HWND: &quot; . hwnd . &quot;`tTitle: &quot; . title . &quot;`tClass: &quot; . class . &quot;`n&quot;
  94. return true <em>; Tell EnumWindows() to continue until all windows have been enumerated.</em>
  95. }</pre>
  96. <p>&nbsp;</p>
  97. <pre class="NoIndent"><em>; Example: The following is a working script that demonstrates how to subclass a GUI window by
  98. ; redirecting its WindowProc to a new WindowProc in the script. In this case, the background
  99. ; color of a text control is changed to a custom color.</em>
  100. TextBackgroundColor := 0xFFBBBB <em>; A custom color in BGR format.</em>
  101. TextBackgroundBrush := DllCall(&quot;CreateSolidBrush&quot;, UInt, TextBackgroundColor)
  102. Gui, Add, Text, HwndMyTextHwnd, Here is some text that is given`na custom background color.
  103. Gui +LastFound
  104. GuiHwnd := WinExist()
  105. <em>; 64-bit scripts must call SetWindowLongPtr instead of SetWindowLong:</em>
  106. SetWindowLong := A_PtrSize=8 ? "SetWindowLongPtr" : "SetWindowLong"
  107. WindowProcNew := <strong>RegisterCallback</strong>(&quot;WindowProc&quot;, &quot;&quot; <em>; Specify &quot;&quot; to avoid fast-mode for subclassing.</em>
  108. , <strong>4</strong>, MyTextHwnd) <em>; Must specify exact ParamCount when EventInfo parameter is present.</em>
  109. WindowProcOld := DllCall(SetWindowLong, Ptr, GuiHwnd, Int, -4 <em>; -4 is GWL_WNDPROC</em>
  110. , Ptr, WindowProcNew, Ptr) <em>; Return value must be set to Ptr or UPtr vs. Int.</em>
  111. Gui Show
  112. return
  113. WindowProc(hwnd, uMsg, wParam, lParam)
  114. {
  115. Critical
  116. global TextBackgroundColor, TextBackgroundBrush, WindowProcOld
  117. if (uMsg = 0x138 &amp;&amp; lParam = A_EventInfo) <em>; 0x138 is WM_CTLCOLORSTATIC.</em>
  118. {
  119. DllCall(&quot;SetBkColor&quot;, Ptr, wParam, UInt, TextBackgroundColor)
  120. return TextBackgroundBrush <em>; Return the HBRUSH to notify the OS that we altered the HDC.</em>
  121. }
  122. <em>; Otherwise (since above didn't return), pass all unhandled events to the original WindowProc.</em>
  123. return DllCall(&quot;CallWindowProc&quot;, Ptr, WindowProcOld, Ptr, hwnd, UInt, uMsg, Ptr, wParam, Ptr, lParam)
  124. }
  125. GuiClose:
  126. ExitApp</pre>
  127. </body>
  128. </html>