0
votes

I want to write an AutoHotkey script which loop a key X number of times.

For example, here's is a script which overwrites the function of ENTER key with function of F2 key in File Explorer.

#IfWinActive ahk_class CabinetWClass
Enter::
Send, {F2}

#IfWinActive ahk_class CabinetWClass
Enter::
Send, {ENTER}

#IfWinActive

The goal is to press ENTER to rename a select file, and then press ENTER to confirm the rename. Pressing ENTER on the same file that have just been renamed should send F2 key again (In case there is typo error).

Currently the second block doesn't work as I'm sending the same key, how to fix this?

3

3 Answers

1
votes

The KeyWait command is your friend in this case.

There is still room to improve on how you handle the second Enter

#IfWinActive ahk_class CabinetWClass
   $Enter::
     sleep,100 ; giving time to detect the first Enter
     Send, {F2}
     Keywait, Enter, T5 D ; wait 5 seconds for the Enter to be pressed down
     If (ErrorLevel == 0)
     {
       Send, {Enter}
       sleep 200
       Send, {F2}
     }
     else
     {
       traytip, , timeout   ; Enter was not pressed down in 5 seconds
     }

   return
1
votes

Basically, it appears you're trying to assign different tasks to the same hotkey and due to this being done seperately ahk is selecting one of the tasks and running with that task and only that task. If loops can be used within hotkeys, so I would suggest using this to rotate between the two expected outcomes. Please see example below:

temp:= 1

enter::
    if(temp==1)
    {
        Send, {ENTER}
        temp:=2
    }
    else if(temp==2)
    {
        Send, {F2}
        temp:=1
    }
return

1::
    Temp:=1
return

2::
    temp:=2
return

^x::ExitApp

I also added in hotkeys for 1/2 to allow you to manually decide the outcome rather than it being specifically assigned in the case of any issues. Oh, and ctrl+x to close the macro.

0
votes

You're trying to rebind the enter key twice. Rebinding a key is like saying "When I press this key, do this:" - in this case it's under an #IfWinActive so it's more like "When this window is open and I press this key..."

When you break that down you have "When I press enter - press F2" as well as "When I press enter, press enter"
What you're wanting to achieve is make the rebind conditional - i.e. it only sends F2 under certain conditions.

It's hard to know how to help without more context. Is there any reason you can't use a different key combination? Like Ctrl + Shift + Enter?

Something like:

+^Enter::send, {F2}