john c. j.
john c. j.

Reputation: 1175

`If WinActive` together with `GetKeyState`

Can anybody explain, why I get "Error" message box?

I think, the code is self-explanatible. I was "surprised" when I discovered it doesn't work for some reason.

(When you press F1 in opened Notepad window, you should see "It works!" message. Instead, I get an "Error" message).

I've tried different ways to fix it, i.e. percents, variables assignments, parentheses, but currently it still doesn't work.

#SingleInstance, Force
SetTitleMatchMode, 2

f1::
+f1::
GetKeyState, shift_state, Shift
msgbox, %shift_state%
if (WinActive("Notepad") and shift_state = D)
    msgbox, It works! By the way, the Shift key is pressed.
else if (WinActive("Notepad") and shift_state = U)
    msgbox, It works! The Shift key is not pressed.
else
    msgbox, error
return

Upvotes: 0

Views: 230

Answers (1)

Relax
Relax

Reputation: 10568

In expressional mode literal strings must be enclosed in double quotes to distinguish them from variables.

https://autohotkey.com/docs/Variables.htm#Expressions

expressional mode:

#SingleInstance, Force 
SetTitleMatchMode, 2

f1::
+f1::
GetKeyState, shift_state, Shift
    msgbox, %shift_state%
if (WinActive("Notepad") and shift_state = "D")
    msgbox, It works! By the way, the Shift key is pressed.
else if (WinActive("Notepad") and shift_state = "U")
    msgbox, It works! The Shift key is not pressed.
else
    msgbox, error
return

traditional mode:

#SingleInstance, Force 
SetTitleMatchMode, 2

f1::
+f1::
GetKeyState, shift_state, Shift
    msgbox, %shift_state%
IfWinActive Notepad
{
    If shift_state = D
        msgbox, It works! By the way, the Shift key is pressed.
    else If shift_state = U
        msgbox, It works! The Shift key is not pressed.
}
else
    msgbox, error
return

Upvotes: 1

Related Questions