how to toggle keyboard mapping in AutoHotKey

2019-07-19 18:12发布

问题:

I would like to map part of my keyboard as a number pad:(my laptop keyboard has no number pad)

j->1
k->2
l->3
u->4
i->5
o->6

I would like to toggle the mapping with a short cut, let's say Control+Alt+M, my code is below, however, I don't know how to reset the mapping:

mode = 0

^!m::
  if (mode = 1)
  {
    mode = 0
    j->1
    k->2
    l->3
    u->4
    i->5
    o->6
  }
  else
  { 
    mode = 1
    u::u ;got error here: duplicate hotkey
  }
return

I got duplicate hotkey error with u::u, seems AHK does not allow mapping more than one key in a script. GetKeyState("NumLock", "P") does not work because I have no NumLock.

I am able to achieve with this code:

^!m::
Suspend
u::4
i::5
o::6
return

But this would toggle entire script, which is apparently not good. So I would like a better solution than this.

回答1:

If you run AKH_L (e.g. AutoHotkey v1.1.10.01), you can use the #IF statement to control the hotkeys (like you would control the hotkeys on an application level with #IfWinActive).

Mode := 0

^!m::
    mode:=!mode ;not! toggle
return

#If mode ; All hotkeys below this line will only work if mode is TRUE
    j::1
    k::2
    l::3
    u::4
    i::5
    o::6
#If


回答2:

Example #1 : Hotkey toggle method

Uses the Hotkey command's toggle option, see [Hotkey]

keys:="jkluio"
Loop,Parse,keys ;create the hotkeys
            Hotkey,$%A_loopField%,Num_pad
Loop,Parse,keys ;turn them off
            Hotkey,$%A_loopField%,Off

^!m::
    Loop,Parse,keys ;toggle hotkeys
            Hotkey,$%A_loopField%,Toggle
return

Num_pad:
    Send % InStr(keys,SubStr(A_ThisHotkey,0))
return

Example #2 : if() toggle method

mode:=0
keys:="jkluio"
Loop,Parse,keys ;create the hotkey
    Hotkey,$%A_loopField%,Num_pad

^!m::
    mode:=!mode ;not! toggle
return

Num_pad:
    if (mode)
        Send % InStr(keys,SubStr(A_ThisHotkey,0))
    else
        Send % SubStr(A_ThisHotkey,0)
return

Note

I recommend the first example, since it is more efficient. The second example is just for "learning" purposes.