Search code examples
autohotkey

AHK's KeyWait+MouseGetPos doesn't work or works RANDOMLY


I'm trying to save user's clicking positions, here are 3 coordinaties for one action: just click-->save coordinates-->second click-->save 2nd coordinates etc. The problem is, my code doesn't work. First, take a look:

CoordMode, Mouse, Screen

KeyWait, LButton, D T3
MouseGetPos , OutputVarX1, OutputVarY1

KeyWait, LButton, D T3
MouseGetPos , OutputVarX2, OutputVarY2

KeyWait, LButton, D T3
MouseGetPos , OutputVarX3, OutputVarY3

IniWrite, %OutputVarX1% %OutputVarY1%, connections.ini, PLACEHOLDER_NAME, click1
IniWrite, %OutputVarX2% %OutputVarY2%, connections.ini, PLACEHOLDER_NAME, click2
IniWrite, %OutputVarX3% %OutputVarY3%, connections.ini, PLACEHOLDER_NAME, click3

MsgBox, Configuration Completed!

It simply waits for three clicks, one after another. In reality:

  1. When I double-click on this script, "Configuration Completed!" window appears immediately. --> Wtf, I only clicked 2 times and just before I launched script!
  2. Okay, I used ENTER to launch script. I wait like 2-3 secs and click somewhere. "Configuration Completed!" --> wtf, I literally just clicked once!
  3. Well, it managed to work, I clicked 3 times. But when I check this .ini file, every each coordinate is same! Or, sometimes, one coordinate is different, and two are same.

So, WTF??? Why it works sooo randomly? I tried adding Sleep 100 between KeyWaits etc. I have no idea wht it behaves like that?


Solution

  • The script has to wait for the button to be released after it has been pressed down. Otherwise it executes the next command immediately.

    CoordMode, Mouse, Screen
    
    KeyWait, LButton, D ; Waits for the button to be pressed down.
    MouseGetPos , OutputVarX1, OutputVarY1
    KeyWait, LButton, L ; Waits for the button to be released.
    
    KeyWait, LButton, D
    MouseGetPos , OutputVarX2, OutputVarY2
    KeyWait, LButton, L
    
    KeyWait, LButton, D
    MouseGetPos , OutputVarX3, OutputVarY3
    KeyWait, LButton, L
    
    IniWrite, %OutputVarX1% %OutputVarY1%, connections.ini, PLACEHOLDER_NAME, click1
    IniWrite, %OutputVarX2% %OutputVarY2%, connections.ini, PLACEHOLDER_NAME, click2
    IniWrite, %OutputVarX3% %OutputVarY3%, connections.ini, PLACEHOLDER_NAME, click3
    
    ; MsgBox, Configuration Completed!
    Run connections.ini