I want to define a shortcut using autohotkey that automates navigation to the Cell Width text box in Word's ribbon menu (i.e. sends the keys Alt,j,l,w while in Word).
My initial attempt at a script introduces an issue where the Up
actions of the physical key presses haven't completed before the keys are sent by the script, causing it to fail.
Although I have a workaround (using sleep 250
, shown further below), I would like to understand whether there is a more elegant solution - e.g. this value was chosen by trial and error, and this workaround may fail on a different machine, or if my laptop is having a bad day.
Essentially, I would like to find a solution that avoids hardcoding a wait duration.
Any suggestions?
The issue
In my initial script I tried to define the hotkey Alt+Shift+p in Word, to send Alt,j,l,w in sequence. This fails and enters the text "jlw" into the active table cell instead.
This is because for keys physically pressed (marked with #
in comments below), the Up
actions are yet to run when the script has already begun sending keys (indicated with $
). This disrupts the send sequence Alt,j,l,w so it fails.
Also note events marked with ?
may be a byproduct of the failed actions.
Script
; Jump to table cell width entry when Alt+Shift+p pressed in Word only
#IfWinActive, ahk_exe WINWORD.EXE
!+p::
Send, {RAlt down}{RAlt up}jlw
Return
Key history
VK SC Type Up/Dn Elapsed Key Comment
-------------------------------------------------------------------------------------------------------------
A4 038 d 1.03 LAlt #
A0 02A d 0.14 LShift #
50 019 h d 0.13 p #, h=Hook Hotkey
A5 138 i d 0.02 RAlt $
A5 138 i u 0.00 RAlt $
11 01D i d 0.00 Control ?
11 01D i u 0.00 Control ?
A4 038 i u 0.00 LAlt #
A0 02A i u 0.00 LShift #
4A 024 i d 0.00 j $
4A 024 i u 0.00 j $
4C 026 i d 0.00 l $
4C 026 i u 0.00 l $
57 011 i d 0.00 w $
57 011 i u 0.00 w $
11 01D i d 0.00 Control ?
A4 038 i d 0.00 LAlt ?
11 01D i u 0.00 Control ?
A0 02A i d 0.00 LShift ?
50 019 s u 0.08 p #
A0 02A u 0.25 LShift ?
A4 038 u 0.00 LAlt ?
Workaround
By adding a sleep 250
statement, the hotkey and sent keys run in the intended sequence. Note no other keys are triggered (nothing indicated with ?
).
Script
; Jump to table cell width entry when Alt+Shift+p pressed in Word only
#IfWinActive, ahk_exe WINWORD.EXE
!+p::
Sleep 250
Send, {RAlt down}{RAlt up}jlw
Return
Key history
VK SC Type Up/Dn Elapsed Key Comment
-------------------------------------------------------------------------------------------------------------
A4 038 d 0.39 LAlt #
A0 02A d 0.20 LShift #
50 019 h d 0.20 p #, h=Hook Hotkey
50 019 s u 0.11 p #
A0 02A u 0.11 LShift #
A4 038 u 0.00 LAlt #
A5 138 i d 0.03 RAlt $
A5 138 i u 0.00 RAlt $
4A 024 i d 0.00 j $
4A 024 i u 0.00 j $
4C 026 i d 0.00 l $
4C 026 i u 0.00 l $
57 011 i d 0.00 w $
57 011 i u 0.00 w $, SUCCESS!