Code: Select all
#SingleInstance Force
SoundBeep, 1500
Run, notepad
WinWaitActive, ahk_exe notepad.exe,, 5
If ErrorLevel
MsgBox, 48, Error, An error occurred while waiting for the window.
MouseMove, 100, 100
fn := Func("function").Bind(12, 12, 3200, 3200) ; Relative to active window
Hotkey, If, % fn
Hotkey, ^w, Hello, On
Hotkey, If
Return
Hello:
MsgBox, 64, Hello, Hello!
Return
function(pX1, pY1, pX2, pY2) {
WinGet, proc, ProcessName, A
MouseGetPos, x, y
ToolTip, Process = %proc%`n`nx = %x%`, y = %y%
If !WinActive("ahk_exe notepad.exe")
Return False
If x between %pX1% and %pX2%
If y between %pY1% and %pY2%
Return True
}
Explanation
I adapted the example from the documentation. It defines fn as a function object before the Hotkey, If statement. This enables that statement to work in setting the context for your Hotkey command, which assigns ^w to the Hello subroutine.
The function has been revised to do some debugging. It displays both the active process name and the relative mouse position in a tooltip. If Notepad is not active, the function returns False and ends. Otherwise, if the relative mouse position is within the stated boundaries, it returns True, and the Hello subroutine is executed, displaying the message box.
I tested the script with Notepad. This demo runs Notepad, and then positions the mouse so that the hotkey will work if pressed before moving the mouse. I showed the earlier screenshot demonstrating that the message box is displayed.
WinActive is an AHK function. As such, it uses expressions as parameters. An example of an expression is a quoted string, as shown.
The script is programmed so that if Notepad is not the active window, the hotkey will not be triggered. In addition, if the mouse position relative to the Notepad window is out of the stated bounds, the hotkey will not be triggered.
The #SingleInstance directive closes an old instance of the same script when the script is run again. This prevents multiple instances of the script from remaining running at the same time.
^w sends something as long as notepad is opened, regardless of the hovering location.
The revised script will assist in providing additional information addressed to your comment, because it will display the process name of the active window, as well as the mouse's position relative to that window. Notepad can be visible without being the active window. If it is the active window, then it has the keyboard focus.