0
votes

Goals:

Run ahk script so that a window stays active. When the user clicks off the window it immediately becomes active again.

This is so an overlay (considered its own window) can be used in a game and that if the overlay is clicked on by accident the game window will become the active window again.

I would also like this to be able to be turned on and off during game play so that the user can alt+tab if necessary.

Problems:

I'm testing my code implementation, so far i have it set up to make a blank notepad file become the active window and stay active.

The problem is the toggle (ctrl+alt+J). I can toggle the code it off just fine but when i toggle it on the window doesn't become active again.

Code:

stop := 0
; 0 = off, 1 = on

while (stop = 0)
{
    IfWinNotActive, Untitled - Notepad
        {
        WinActivate, Untitled - Notepad
        }
}

return

^!j::
    stop  := !stop

    if (stop = 0){
        MsgBox, stop is off.
    }
    else{
        MsgBox, stop is  on.
    }

return
1

1 Answers

0
votes

The reason it doesn't work after you toggle it off is that While only runs until is evaluates to false. Even if what it would evaluate later becomes true again, it won't restart.
Here's what you can do to make your current code work:

stop := 0
; 0 = off, 1 = on

labelWinCheck: ; label for GoSub to restart while-loop
while (stop = 0)
{
    IfWinNotActive, Untitled - Notepad
    {
        WinActivate, Untitled - Notepad
    }
    Sleep , 250 ; added sleep (250 ms) so CPU isn't running full blast
}
return

^!j::
    stop  := !stop

    if (stop = 0){
        MsgBox, stop is off.
    } else {
        MsgBox, stop is on.
    }
GoSub , labelWinCheck ; restarts while-loop
return

There are a couple of different ways that I would look at to achieve your goal.

  • Easy: use SetTimer instead of While.
stop := 0
SetTimer , labelWinCheck , 250 ; Repeats every 250 ms

labelWinCheck:
If !WinActive( "Untitled - Notepad" )
    WinActivate , Untitled - Notepad
Return

^!j::
SetTimer , labelWinCheck , % ( stop := !stop ) ? "off" : "on"
MsgBox , % "stop is " . ( stop ? "on" : "off" )
Return
  • Advanced: us OnMessage() to monitor WinActivate events. I don't have a working example of this as that would take a bit of research for me, but here is a link for a solution I made to monitor keyboard events, Log multiple Keys with AutoHotkey. The links at the bottom may especially prove useful.