The script only works if it is written from the first line.

Get help with using AutoHotkey and its commands and hotkeys
reluct
Posts: 88
Joined: 28 Nov 2018, 05:07

The script only works if it is written from the first line.

14 Aug 2019, 12:02

Code: Select all

ClipNew := clipboard 
OnClipboardChange:
ClipOld := ClipNew
ClipNew := clipboard 
Numpad8:: SendInput %ClipOld%
Why this script only works if written at the beginning of the file?
But if another script is written before it, then this one starts to behave strangely. For example, when I copy text, the script instead pastes the previous clip from the clipboard.
gregster
Posts: 3289
Joined: 30 Sep 2013, 06:48

Re: The script only works if it is written from the first line.

15 Aug 2019, 00:31

It depends on the code that you insert before it.

The initial ClipNew := clipboard line will only be executed, if it is reachable - like in the snippet you posted. There it's part of the auto-execute section of the script (aka top of the script): https://www.autohotkey.com/docs/Scripts.htm#auto :
After the script has been loaded, it begins executing at the top line, continuing until a Return, Exit, hotkey/hotstring label, or the physical end of the script is encountered (whichever comes first). This top portion of the script is referred to as the auto-execute section.

If you make this line unreachable by, for example, putting a return or a hotkey defintion above it, then ClipNew will be empty on the first iteration of ClipOld := ClipNew. So, make sure that code gets executed.

If this doesn't answer your question, please elaborate and post an example (and describe the expected and actual outcomes...)

Btw, your snippet's code execution will fall through into the code of the label OnClipboardChange on first execution. Because a normal (= no hotkey/hotstring) label doesn't end the auto-execute section - not sure, if that was intended by you or not. But that's something that'll also change, if you insert some other code above it that ends auto-execution.
Edit: Since the docs state "The label also runs once when the script first starts" it's not relevant here, because the label will be excuted anyway on first run.
reluct
Posts: 88
Joined: 28 Nov 2018, 05:07

Re: The script only works if it is written from the first line.

15 Aug 2019, 01:15

The only thing I realized from all this is that the command at the beginning of the script does not end. But how to fix it?
I just need copy previous clip from clipboard. And then paste it.
gregster
Posts: 3289
Joined: 30 Sep 2013, 06:48

Re: The script only works if it is written from the first line.

15 Aug 2019, 02:17

Perhaps like this (since you said that the snippet is ok, but combining it with other code poses problems):

Code: Select all

; auto-exec section:
ClipNew := clipboard 	; this line is still reachable
; some other stuff you want to have here
return	; end of auto-execute section

; other labels, hotkeys, hotstrings

OnClipboardChange:		; docs: "The label also runs once when the script first starts."
ClipOld := ClipNew
ClipNew := clipboard 
return 
Numpad8:: SendInput %ClipOld%	; pastes "old", previous clipboard (but current clipboard on script start)
(If this is not want you want, please show example code that demonstrates the problem.)
swagfag
Posts: 3001
Joined: 11 Jan 2017, 17:59

Re: The script only works if it is written from the first line.

15 Aug 2019, 12:21

then
gregster wrote:
15 Aug 2019, 02:17
...please show example code that demonstrates the problem.)
gregster
Posts: 3289
Joined: 30 Sep 2013, 06:48

Re: The script only works if it is written from the first line.

15 Aug 2019, 12:40

reluct wrote:
15 Aug 2019, 03:36
This code is not working.
In what sense? So far, it is nearly the same code that you said would work for you. I just added some comments about controlling the code flow (and two returns which should be largely redundant as long as you don't insert more code).
Since I don't know what code you are inserting (your exact work flow I don't know either), I cannot tell you what might be the problem.

We could start by looking at a concrete example of the behaviour you described here:
But if another script is written before it, then this one starts to behave strangely.
Please show that "other script" and how you inserted it into the existing code. Also, please describe what changed after inserting and what you expected to happen instead.
reluct
Posts: 88
Joined: 28 Nov 2018, 05:07

Re: The script only works if it is written from the first line.

15 Aug 2019, 13:55

Code: Select all

sc15B:: 
   Send, :
Return


$^1:: ; Поиск с начала строки. AkelPad
   Send ^{sc21}{Raw}^
   Send ^{sc2f}{Enter}
   Return

$^2:: ; 
   Send ^{sc21}\[trn\] .*\[/trn\]{Enter}
   Return

$^3:: ; Добавление таб[m1] в начале строки для редактирования словаря. AkelPad
   Send {scF}[m1]
   Return

$^sc10:: ; Закрыть все окна(win+d) переназначено на ctrl+q
Send {sc15B Down}{sc20}{sc15B Up} ; (win+d)
Return

sc4B:: ; Numpad4 Скрипт GD открыть слово в новой вкладке 
If A_Cursor=Unknown ; ;The hand-shaped cursors (pointing and grabbing) are classified as Unknown
{
	Send, {sc1D Down}
	Click
	Send, {sc1D Up}
	Sleep, 1000
	MouseGetPos, xpos, ypos
	MouseClick, left, 1691, 120, , 0 ; [WhichButton , X, Y, ClickCount, Speed, D|U, R]
	MouseMove, xpos, ypos, 0
}
Else If A_Cursor=IBeam ; курсор как при впечатать текст
{
	Send, {sc1D Down}
	Click, 2
	Send {sc1D Up}
	Sleep, 1000
	MouseGetPos, xpos, ypos
	MouseClick, left, 1691, 120, , 0 ; [WhichButton , X, Y, ClickCount, Speed, D|U, R]
	MouseMove, xpos, ypos, 0
}
Return

CapsLock:: ; Cмена языка 
Send {sc15B Down}{sc39}{sc15B Up} ; win+space
Return

sc43:: ; запись ролика по нажатию F9
   Send, {Numpad1}
Sleep 10
Send, {Space}
Return

; Numpad1 Badcam начало записи
; Numpad2 Скрипт Поиск в Обозревателе анки
; Numpad3 Пусто???
; Numpad4 Скрипт GD открыть слово в новой вкладке + Anki  Numpad4 клик по Редактирование(без движения мыши) Ескейп - проигрывается звук и карточка с начала
; Numpad5 ,{space}
; Numpad6 Скрипт translate.google.com
; Numpad7 Alt+F4
; Numpad8 

 ; Скрипт для того чтобы окно было всегда поверх других оконо: MButton:: Winset, Alwaysontop, , A 

MButton:: ; LCtrl для ABBYY Lyngvo на среднюю кнопку мыши
Send, {sc1D Down}
Sleep, 3000
Send, {sc1D Up}
Return

Numpad5::
Send, ,{space}
Return
 
Numpad6::
Send, {sc1D Down}{sc2E}{sc1D Up}
Run, https://translate.google.com/
Sleep, 3000
Send, {sc1D Down}{sc2F}{sc1D Up} 
Send, {sc1C}
Return

^!p::
Send, {sc1D Down}{sc2E}{sc1D Up}
MouseGetPos, xpos, ypos
	MouseClick, left, 1619, 115, 3, 0 ; [WhichButton , X, Y, ClickCount, Speed, D|U, R]
Send, {sc1D Down}{sc2F}{sc1D Up}
    MouseClick, left, 1736, 114, , 0 ; [WhichButton , X, Y, ClickCount, Speed, D|U, R]
MouseMove, xpos, ypos, 0
Return

Numpad7:: ; Alt+F4 закрыть окно
Send, {sc38 Down}{sc3E}{sc38 Up}  
Return

; Листание Master-Pdf

WheelUp:: 
MouseGetPos, MouseX, MouseY
PixelGetColor, color, %MouseX%, %MouseY%
if (color = 0x282828)
{
Send, {sc149}
}
Else if (color <> 0x282828)
{
	Click, WheelUp
}
return

WheelDown::
MouseGetPos, MouseX, MouseY
PixelGetColor, color, %MouseX%, %MouseY%
if (color = 0x282828)
{
	Send, {sc151}
}
Else if (color <> 0x282828)
{
		Click, WheelDown
}
return

; Листание Foxit


#IfWinActive ahk_class classFoxitPhantom
WheelUp::
MouseGetPos, MouseX, MouseY
PixelGetColor, color, %MouseX%, %MouseY%, RGB
if (color = 0xABABAB)
{
Send, {sc149}
}
Else if (color <> 0xABABAB)
{
	Click, WheelUp
}
return

#IfWinActive ahk_class classFoxitPhantom
WheelDown::
MouseGetPos, MouseX, MouseY
PixelGetColor, color, %MouseX%, %MouseY%, RGB
if (color = 0xABABAB)
{
	Send, {sc151}
}
Else if (color <> 0xABABAB)
{
		Click, WheelDown
}
return

$^4::
WinGetActiveStats, Title, Width, Height, X, Y
WinGet, Process, ProcessName, A
MsgBox, The active window “%Title%” is %Width% wide, %Height% tall, and positioned at %X%`,%Y%. Its process is %Process%.
return

sc35:: ; запятая до переназначения смены языка на Tab
   Send, ,
Return

RShift:: 
   Send, .	
Return

LAlt:: 
   Send, `;	
Return

RControl::
   Send, ?
Return

; Anki Numpad3 Скрипт Поиск в Обозревателе анки

Numpad3:: 
if WinExist("ahk_exe anki.exe") 
	WinActivate, ahk_exe anki.exe
Send, {sc1}{scA}{sc1D Down}{sc2F}{sc1D Up}{sc1C} ; Esc - 9 - LCtrl вниз - v - LCtrl вверх - enter
Return

; Anki Numpad2 Поиск в Обозревателе анки по Вопрос2345

Numpad2::
clipboard = "Вопрос:*%clipboard%*" or "Вопрос 2:*%clipboard%*" or "Вопрос 3:*%clipboard%*" or "Вопрос 4:*%clipboard%*" or "Вопрос 5:*%clipboard%*"
if WinExist("ahk_exe anki.exe") 
WinActivate, ahk_exe anki.exe
Send, {sc1}{scA}{sc1D Down}{sc2F}{sc1D Up}{sc1C} ; Esc - 9 - LCtrl вниз - v - LCtrl вверх - enter
Return

; Anki  Numpad4 клик по Редактирование(без движения мыши) Ескейп - проигрывается звук и карточка с начала

#IfWinActive ahk_class QWidget
scF::
ControlClick, x24 y1177, ahk_class QWidget,, Left, 1, NA
Send {sc1}
return

; Anki NumpadLeft

#IfWinActive ahk_class QWidget
sc4B:: 
MouseGetPos, xpos, ypos
	ControlClick, x24 y1177, ahk_class QWidget,, Left, 1, NA
	MouseMove, xpos, ypos, 0
Send {sc1}
return

; Anki 1 видео12345 ctrl+alt+w

#IfWinActive ahk_class QWidget
^!w::
clipboard = [sound:video/%clipboard%.avi] [sound:video/%clipboard% (2).avi] [sound:video/%clipboard% (3).avi] [sound:video/%clipboard% (4).avi] [sound:video/%clipboard% (5).avi]
send {sc1D Down}{sc2F}{sc1D Up}
return

; Anki 2 видео12345 ctrl+alt+e

; auto-exec section:
ClipNew := clipboard 	; this line is still reachable
; some other stuff you want to have here
return	; end of auto-execute section

; other labels, hotkeys, hotstrings

OnClipboardChange:		; docs: "The label also runs once when the script first starts."
ClipOld := ClipNew
ClipNew := clipboard 
return 
Numpad8:: SendInput %ClipOld%	; pastes "old", previous clipboard (but current clipboard on script start)
This my AHK file.
gregster
Posts: 3289
Joined: 30 Sep 2013, 06:48

Re: The script only works if it is written from the first line.

15 Aug 2019, 20:03

Ok, so you pasted it to the end of a file... two problems are evident:
  • Another problem (probably, but it depends on what you intend) is that the Numpad8:: SendInput %ClipOld% hotkey definition is located under the #IfWinActive ahk_class QWidget line/directive (see ^!w hotkey) which is still relevant for all hotkeys beneath it, as long as you don't close this section of context-sensitivity (for example, with #IfWinActive - without any parameter). That means, at the moment, Numpad8 only works, if a window is active that has the ahk_class QWidget wintitle property.

To solve these problems, I would
  • and - if Numpad8 should generally work - I would add a line like #If or #IfWinActive (no parameters!) somewhere above its hotkey definition, so Numpad8 won't be context-sensitive any longer (but I am not even sure, if this is your intention).
That means (one possibility):

Code: Select all

; auto-exec section/top of the script:
ClipNew := clipboard 	; this line is reachable and executed once, when the script starts
return ; end of auto-execute section

sc15B:: 
   Send, :
Return

$^1:: ; Поиск с начала строки. AkelPad
   Send ^{sc21}{Raw}^
   Send ^{sc2f}{Enter}
   Return
 
 ;[...]  your other hotkeys here, like before
 
#IfWinActive ahk_class QWidget
^!w::
clipboard = [sound:video/%clipboard%.avi] [sound:video/%clipboard% (2).avi] [sound:video/%clipboard% (3).avi] [sound:video/%clipboard% (4).avi] [sound:video/%clipboard% (5).avi]
send {sc1D Down}{sc2F}{sc1D Up}
return
#IfWinActive	; ends section of context-sensitivity

OnClipboardChange:		; docs: "The label also runs once when the script first starts."
ClipOld := ClipNew
ClipNew := clipboard 
return 

Numpad8:: SendInput %ClipOld%	; pastes "old", previous clipboard (but current clipboard at script start)
reluct
Posts: 88
Joined: 28 Nov 2018, 05:07

Re: The script only works if it is written from the first line.

15 Aug 2019, 22:02

I don’t see the difference if I still have to write part of this code from the first line.
In addition, for a reason unknown to me, your code conflicts with one of the programs (SpartanClips).
gregster
Posts: 3289
Joined: 30 Sep 2013, 06:48

Re: The script only works if it is written from the first line.

15 Aug 2019, 23:19

reluct wrote:
15 Aug 2019, 22:02
I don’t see the difference if I still have to write part of this code from the first line.
Not necessarily in the first line, but as part of the auto-execute section. I am just explaining to you the logic of the code flow in AHK and why your snippet above reacts differently, if you put hotkey definitions above it. After all, this was your question about that specific snippet of code you presented: "Why this script only works if written at the beginning of the file?"

If you have some code that should be executed directly at script start without any additional user action (like pressing a button), you will have to put it into the auto-execute section or at least call that code from this section somehow (for example, with gosub and another label or a timer). But if a line is unreachable, it won't be executed at all.

When you start the script, there is obviously no previous clipboard available to the script, so if you don't need the current clipboard in the ClipOld variable at that point, you can of course simply remove this line completely.
reluct wrote:
15 Aug 2019, 22:02
In addition, for a reason unknown to me, your code conflicts with one of the programs (SpartanClips).
It seems that SpartanClips is some third-party clipboard manager. I could imagine that it could come into conflict with AHK's clipboard handling (or other clipboard managers), but I fail to see how my minimal re-arrangement of your code should have made a difference. But again, without a specific and concise problem description it's hard to make any meaningful suggestion that could possibly mitigate the issue. I am just an average guesser.
reluct
Posts: 88
Joined: 28 Nov 2018, 05:07

Re: The script only works if it is written from the first line.

16 Aug 2019, 00:10

It seems that SpartanClips But again, without a specific and concise problem description it's hard to make any meaningful suggestion that could possibly mitigate the issue. I am just an average guesser.
AHK pastes current clip from clipboard.
gregster
Posts: 3289
Joined: 30 Sep 2013, 06:48

Re: The script only works if it is written from the first line.

16 Aug 2019, 00:21

You mean when the script starts and there is no previous clipboard saved? Yes, that's what your original code does - I didn't change that.
reluct
Posts: 88
Joined: 28 Nov 2018, 05:07

Re: The script only works if it is written from the first line.

16 Aug 2019, 01:20

I mean that the program does not paste the previous clip, it paste the one I just copied.
gregster
Posts: 3289
Joined: 30 Sep 2013, 06:48

Re: The script only works if it is written from the first line.

16 Aug 2019, 01:49

My proposed code should be functionally identical to your original code snippet. I literally didn't change anything concerning the variable assignments.

Can you show the differences in the results of the two scripts in combination with the third-party program? I would like to reproduce it. Hence, it would be good if you could document your exact steps with the two variants - and the differing results.

In which way are the results different, if you close the clipboard manager, before you run both script variants?
hd0202
Posts: 140
Joined: 04 Oct 2013, 03:07
Location: Germany near Cologne

Re: The script only works if it is written from the first line.

16 Aug 2019, 02:22

the script should start (see the first post):

Code: Select all

ClipNew := clipboard 
ClipOld := ClipNew
Hubert
reluct
Posts: 88
Joined: 28 Nov 2018, 05:07

Re: The script only works if it is written from the first line.

16 Aug 2019, 02:56

gregster wrote:
16 Aug 2019, 01:49
Can you show the differences in the results of the two scripts in combination with the third-party program?
The difference is that in one case I run third-party clipboard manager and the other does not.
gregster
Posts: 3289
Joined: 30 Sep 2013, 06:48

Re: The script only works if it is written from the first line.

16 Aug 2019, 13:28

Splendid!

But I actually asked what differing results or behaviours you observe, since you said there are conflicts with the third-party program and that there seem to be differences between your original code and my slightly altered code.

Look, if it is too much to ask that you provide detailed information and take active part in the debugging, then the chance that we can help, rapidly goes down.
reluct
Posts: 88
Joined: 28 Nov 2018, 05:07

Re: The script only works if it is written from the first line.

16 Aug 2019, 14:48

gregster wrote:
16 Aug 2019, 13:28
Splendid!

But I actually asked what differing results or behaviours you observe, since you said there are conflicts with the third-party program and that there seem to be differences between your original code and my slightly altered code.

Look, if it is too much to ask that you provide detailed information and take active part in the debugging, then the chance that we can help, rapidly goes down.
The difference is that when I use your code AHK:
reluct wrote: does not paste the previous clip, it paste the one I just copied.
In both cases, I just copy the code and press Numpad8.

Conflicts with the third-party program = code not work.
gregster
Posts: 3289
Joined: 30 Sep 2013, 06:48

Re: The script only works if it is written from the first line.

16 Aug 2019, 22:30

Alrighty, let's first check this claim (before we look at the third-party program - please shut it down for testing the AHK script versions):
reluct wrote:
16 Aug 2019, 14:48
The difference is that when I use your code AHK:
reluct wrote: does not paste the previous clip, it paste the one I just copied.
In both cases, I just copy the code and press Numpad8.

So, let's look at the results when we use your original script and my only slightly altered version.
In both cases, I got the same results:

Code: Select all

Start like this:
1. Copy string "original" to the clipboard (before script start)
2. Start the script - make sure that no other scripts (or clipboard managers) are running at the same time

Now, while the script is running, I alternately used Numpad8 and ctrl+v to check, then I copied the next string and checked again. 
With these results:
3. Numpad8 sends "original" (there was no "previous" clipboard available); Ctrl+v sends "original", too 
4. Copy the string "first"
5. Numpad8 sends "original" again (it is now the "previous" clipboard: oldclip); Ctrl+v sends "first"
6. Copy the string "second"
7. Numpad8 sends "first" (it is now the "previous" clipboard: oldclip); Ctrl+v sends "second"
8. Copy the string "third"
9. Numpad8 sends "second" (it is now the "previous" clipboard: oldclip); Ctrl+v sends "third"
10. and so on...

the strings I used:
/*
original
first		
second
third
*/

Alternate view of the results:

Code: Select all

output "original" script (first post) - keys repeatedly pressed:
			Numpad8:							Ctrl+v:
originaloriginaloriginaloriginal	originaloriginaloriginaloriginal			Step 3	
originaloriginaloriginaloriginal 	firstfirstfirstfirstfirstfirst				Step 5	
firstfirstfirstfirstfirstfirst 		secondsecondsecondsecondsecondsecond		Step 7	
secondsecondsecondsecondsecond 		thirdthirdthirdthirdthirdthirdthird			Step 9	

output "my" version - keys repeatedly pressed:
			Numpad8:							Ctrl+v:
originaloriginaloriginaloriginal 	originaloriginaloriginaloriginal			Step 3	
originaloriginaloriginaloriginal	firstfirstfirstfirstfirstfirstfirst			Step 5		
firstfirstfirstfirstfirstfirst		secondsecondsecondsecondsecondsecond		Step 7	
secondsecondsecondsecondsecond		thirdthirdthirdthirdthirdthirdthird			Step 9	


;-----------------------------------------------------------------------------------------

output "my" version - but without the line "ClipNew := clipboard" in the auto-exec-section - keys repeatedly pressed:
			Numpad8:							Ctrl+v:
			(empty)					originaloriginaloriginaloriginal			Step 3		
originaloriginaloriginaloriginal	firstfirstfirstfirstfirstfirstfirst			Step 5		
firstfirstfirstfirstfirstfirst		secondsecondsecondsecondsecondsecond		Step 7		
secondsecondsecondsecondsecond		thirdthirdthirdthirdthirdthirdthird			Step 9	
I would say, the results are like it could be expected (that means, identical) when we look at the code (while not forgetting the special behaviour of the OnClipboardChange label and the rules of the auto-execute section).

Can we agree on these results?
If not, please show yours and please make sure again that no other interfering scripts or programs are running at the time of the test.

Return to “Ask For Help”

Who is online

Users browsing this forum: Rohwedder, ulraf and 60 guests