Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoHotKey strange issue with Copy (Ctrl-C) every other execution

Tags:

autohotkey

I'm new to writing my own AutoHotKey scripts so this just has to be something stupid I'm missing here.

The intent of the script is for the user to select some text and press the hot-key (Win-W). The menu pops-up and they click the menu item. The selected text should then be copied to the clipboard. That's all i'm trying to do right now.

The problem is that it works the first time, then fails, then works, then fails, etc. It basically only works every other time.

I'm running Win7 x64 with the latest AutoHotKey_l (unicode 32bit).

I have a timeout on the ClipWait, and it basically just waits, never receives the copied text, and issues an ErrorLevel 1.

Here's the code:

#SingleInstance force
; EXAMPLE #2: This is a working script that creates a popup menu that is displayed when the user presses the Win-w hotkey.

; Create the popup menu by adding some items to it.
Menu, MyMenu, Add, Demo, Demo

return  ; End of script's auto-execute section.

Demo:
clipboard =  ; Start off empty to allow ClipWait to detect when the text has arrived.
Send ^c
ClipWait, 2  ; Wait for the clipboard to contain text.
if ErrorLevel = 1
{
    MsgBox Copy failed
}
else
{
    MsgBox Copy worked
}
return

#w::Menu, MyMenu, Show  ; i.e. press the Win-w hotkey to show the menu.

Any help would be greatly appreciated.

like image 596
kman Avatar asked Apr 12 '12 14:04

kman


1 Answers

When you have a script that behaves sporadically, and/or differently in other programs,
the first thing to try is simulating a key-press duration and/or delay period between keys.
This is because some programs aren't designed to handle the speed that AutoHotkey sends
artificial keystrokes.

Here is the most basic example:

f1::
Send, {ctrl down}
Sleep, 40
Send, {c down}
Sleep, 40
Send, {c up}
Sleep, 40
Send, {ctrl up}
Return

We have several ways to make it more concise.
The easiest (yet not always desirable since it blocks during delays, unlike sleep)
is the SetKeyDelay command, which only works for the SendEvent and SendPlay modes.

f2::
SetKeyDelay, 40 ; could be set at the top of the script instead.
Send, {ctrl down}{c down}{c up}{ctrl up}
Return 

Those using AHK_L can make use of a for-loop and an array:

f3::
For i, element in array := ["{ctrl down}","{c down}","{c up}","{ctrl up}"] {
   Sendinput, %element%
   Sleep, 40
} Return

And those using AHK basic (or AHK_L) can use Loop, Parse:

f4::
list := "{ctrl down},{c down},{c up},{ctrl up}"
Loop Parse, list, `,
{
    Sendinput, %A_LoopField%
    Sleep, 40
} Return 

It's useful to read about the three Sendmodes.
More information can be found at the bottom of the Send command's page.

like image 138
Honest Abe Avatar answered Sep 22 '22 13:09

Honest Abe