Newly converted script not working

Get help with using AutoHotkey (v2 or newer) and its commands and hotkeys
pgeugene
Posts: 40
Joined: 27 Jun 2019, 04:36

Newly converted script not working

16 Feb 2024, 04:25

I copied portion of V1 script and used converter tool to convert to V2 script but received error upon launching the new V2 script
The script is to copy selected text and pasted it to the window I have chosen with a hotkey stated in the script

V1 script

Code: Select all

+!c::  ; alt+shift+c to copy to the selected window

    If !WinTag
    {
        MsgBox, , Capsy CopyToApp, You pressed the combination of CopyToApp. First, tag a target window in NotePad
        , WordPad or a GUI edit field.`r`r 1
        . Activate window`n 2
        . Press Ctrl+Win+Shift+Z
        return
    }

    OldClipboard:= ClipboardAll
    ; Clipboard:= ""
    sleep 500
    Send, ^c ;copies selected text
    ClipWait,1
    If ErrorLevel
    {
        MsgBox, , Capsy CopyToApp, No text selected!
        return
    }
    IfWinExist, %winTitlePart%
    {
        ;Save the currently active window title
        WinGetTitle, actWin, A

        ; If OneNote is not active, activate it now
        IfWinNotActive, %winTitlePart%
            WinActivate, %winTitlePart%

        ; Check again, if ON active then paste else error
        IfWinActive, %winTitlePart%
        {
            Send, ^v`r`r ; Use sendplay to avoid unexpected interactions with Win key
            ; Switch window back to previously active
            WinActivate, %actWin%
        }
        sleep 500
    }
    Else
    {
        MsgBox, Window < "%winTitlePart%" > does not Exist!
    }
    Clipboard := OldClipboard
return

^#+z:: ;Ctrl+win+shift+z tag a window as a copy destination
    ; Click, %A_CaretX%, %A_CaretY%
    MouseGetPos, , , WinTag, Control
    WinGetTitle, winTitlePart, ahk_id %WinTag%
    MsgBox, , Capsy CopyToApp, " %winTitlePart% " is tagged as the destination window!`r - Press < Alt+Shift+C > to copy selection to this app.`r - Press < Ctrl+Win+Shift+R > to reset.
return

^#+r:: ;Ctrl+win+shift+r tag a window as a reset destination
    WinActivate, ahk_id %WinTag%
    MsgBox, , Capsy CopyToApp, CopyToApp windows is reset!, 3
    WinTag:=""
return
V2 script

Code: Select all

+!c::  ; alt+shift+c to copy to the selected window

{ ; V1toV2: Added bracket
    If !WinTag
    {
        MsgBox("You pressed the combination of CopyToApp. First, tag a target window in NotePad        , WordPad or a GUI edit field.`r`r 1        . Activate window`n 2        . Press Ctrl+Win+Shift+Z", "Capsy CopyToApp", "")
        return
    }

    OldClipboard:= ClipboardAll()
    ; Clipboard:= ""
    Sleep(500)
    Send("^c") ;copies selected text
    Errorlevel := !ClipWait(1)
    If ErrorLevel
    {
        MsgBox("No text selected!", "Capsy CopyToApp", "")
        return
    }
    if WinExist(winTitlePart)
    {
        ;Save the currently active window title
        actWin := WinGetTitle("A")

        ; If OneNote is not active, activate it now
        if !WinActive(winTitlePart)
            WinActivate(winTitlePart)

        ; Check again, if ON active then paste else error
        if WinActive(winTitlePart)
        {
            Send("^v`r`r") ; Use sendplay to avoid unexpected interactions with Win key
            ; Switch window back to previously active
            WinActivate(actWin)
        }
        Sleep(500)
    }
    Else
    {
        MsgBox("Window < `"" winTitlePart "`" > does not Exist!")
    }
    A_Clipboard := OldClipboard
return
} ; V1toV2: Added Bracket before hotkey or Hotstring

^#+z:: ;Ctrl+win+shift+z tag a window as a copy destination
    ; Click, %A_CaretX%, %A_CaretY%
{ ; V1toV2: Added bracket
    MouseGetPos(, , &WinTag, &Control)
    winTitlePart := WinGetTitle("ahk_id " WinTag)
    MsgBox("`" " winTitlePart " `" is tagged as the destination window!`r - Press < Alt+Shift+C > to copy selection to this app.`r - Press < Ctrl+Win+Shift+R > to reset.", "Capsy CopyToApp", "")
return
} ; V1toV2: Added Bracket before hotkey or Hotstring

^#+r:: ;Ctrl+win+shift+r tag a window as a reset destination
{ ; V1toV2: Added bracket
    WinActivate("ahk_id " WinTag)
    MsgBox("CopyToApp windows is reset!", "Capsy CopyToApp", "T3")
    WinTag:=""
return
} ; V1toV2: Added bracket in the end
Attachments
backgroundsave.png
backgroundsave.png (16.74 KiB) Viewed 325 times
User avatar
mikeyww
Posts: 27366
Joined: 09 Sep 2014, 18:38

Re: Newly converted script not working

16 Feb 2024, 06:27

Hello,
  1. Hotkeys are now functions in AHK v2.
  2. As with v1, variables in functions are local to the function, by default. See v2 documentation about variable scope.
  3. In v2, a variable must be defined before it is accessed.
  4. Assigning a global variable inside a function requires declaring the variable as global, inside the function. The documentation has examples of this.

Code: Select all

#Requires AutoHotkey v2.0
WinTag := 0
F3::Global WinTag := 1
F4::Global WinTag := 2
F5::MsgBox WinTag
pgeugene
Posts: 40
Joined: 27 Jun 2019, 04:36

Re: Newly converted script not working

17 Feb 2024, 03:11

mikeyww wrote:
16 Feb 2024, 06:27
Hello,
  1. Hotkeys are now functions in AHK v2.
  2. As with v1, variables in functions are local to the function, by default. See v2 documentation about variable scope.
  3. In v2, a variable must be defined before it is accessed.
  4. Assigning a global variable inside a function requires declaring the variable as global, inside the function. The documentation has examples of this.

Code: Select all

#Requires AutoHotkey v2.0
WinTag := 0
F3::Global WinTag := 1
F4::Global WinTag := 2
F5::MsgBox WinTag
Thank you for your reply.
Unfortunately I still can't fully understand documentation examples in order to fix my script.
Can you help me to fix it for me ?
niCode
Posts: 320
Joined: 17 Oct 2022, 22:09

Re: Newly converted script not working

17 Feb 2024, 05:03

I'm gonna give some explanation on what seems to be your biggest gap in knowledge here which is variable scope along with some examples that should allow you to understand how to fix your code.

Variable scope is different in v2 when it comes to hotkeys. In v1, you could create and assign variables in a hotkey and they would be accessible everywhere (global scope) which is what you're expecting to happen. In v2, hotkeys are functions. That means when you create a variable inside a hotkey, that variable is only accessible to the hotkey (local scope).
The simple answer is to make global variables and allow the hotkeys to change those values. Global variables are typically frowned upon but since you're still learning, I think it's best to take it one step at a time and not overwhelm you with other ways to solve this.

*One thing to note about global variables: functions can read global variables without a problem (unless a local variable with the same name exists), but if you want to change the value of a global variable inside a function, you have to explicitly tell the function to do so.

Let's look at some examples to show what works and what doesn't.

Code: Select all

WinTag := 0                     ; global variable

1:: {
    MouseGetPos(,, &WinTag)     ; get window id under mouse
}

2:: {
    MsgBox(WinTag)              ; show WinTag variable
}
In the above, if you press 2, the hotkey can read the global variable and will show 0. Pressing 1 will get the id of the window and assign it to WinTag. Now if you press 2 again, you will get...still 0. By default, the hotkey created a local variable called WinTag. Yep, the same name, but a different variable that exists only inside that hotkey.

Okay, let's look at some ways to allow the hotkey to use the global variable.

Code: Select all

1:: {
    global                      ; declare all variables as global
    MouseGetPos(,, &WinTag)     ; get window id under mouse
}
or

Code: Select all

1:: {
    global WinTag               ; declare all variables as global
    MouseGetPos(,, &WinTag)     ; get window id under mouse
}
In the first snippet, using the word global by itself at top of the hotkey tells the hotkey that all variables here are going to be global. If you define a new variable in the hotkey, that variable will also be global. I don't recommend this method.
In the second snippet, you're telling the function that if you use the variable WinTag, it will be global. It technically has the shortcoming of the first snippet, but because you have to specify the variable, you don't have to worry about newly created variables being able to be accidentally accessed by other functions.
The above methods work and will change the global variable (assuming that variable is defined in the global scope such as the very first example).


You can also assign a value when defining a global variable in a hotkey. I couldn't show it in the previous examples because MouseGetPos is one of those functions that doesn't return a value, it uses variable references to get values. Here's an example of directly assigning to a global variable:

Code: Select all

WinTag := 0                     ; global variable
winTitlePart := 0               ; global variable

1:: {
    global WinTag
    MouseGetPos(,, &WinTag)
    global winTitlePart := WinGetTitle('ahk_id ' WinTag)
}

2:: {
    MsgBox(WinTag '`n' winTitlePart)
}
And once you tell the function that a particular variable is global, you don't have to use the keyword global in the hotkey again. For example:

Code: Select all

1:: {
    global WinTag
    MouseGetPos(,, &WinTag)
    global winTitlePart := WinGetTitle('ahk_id ' WinTag)
    winTitlePart := 'hello'
}
In the above, the global variable winTitlePart will be hello because you already told the function every instance of winTitlePart is the global version.


In short:
  • Variables have to be defined before trying to read their value. After all, if they weren't given a value, how could it return a value? (v1 had default values so you didn't have to do this in v1).
  • By default, variables inside functions (and hotkeys) are local and can't be accessed outside the function.
  • If a function needs to be able to change a global variable, you have to tell it to do so in one of the ways mentioned above.

Hopefully this helps you understand why the variables weren't working in your script and how you can solve them.
Rohwedder
Posts: 7774
Joined: 04 Jun 2014, 08:33
Location: Germany

Re: Newly converted script not working

17 Feb 2024, 05:04

Hallo,
(untested), try:

Code: Select all

#Requires AutoHotkey v2.0
Global WinTag := winTitlePart := ""
+!c::  ; alt+shift+c to copy to the selected window

{ ; V1toV2: Added bracket
	Global
    If !WinTag
    {
        MsgBox("You pressed the combination of CopyToApp. First, tag a target window in NotePad        , WordPad or a GUI edit field.`r`r 1        . Activate window`n 2        . Press Ctrl+Win+Shift+Z", "Capsy CopyToApp", "")
        return
    }

    OldClipboard:= ClipboardAll()
    ; Clipboard:= ""
    Sleep(500)
    Send("^c") ;copies selected text
    Errorlevel := !ClipWait(1)
    If ErrorLevel
    {
        MsgBox("No text selected!", "Capsy CopyToApp", "")
        return
    }
    if WinExist(winTitlePart)
    {
        ;Save the currently active window title
        actWin := WinGetTitle("A")

        ; If OneNote is not active, activate it now
        if !WinActive(winTitlePart)
            WinActivate(winTitlePart)

        ; Check again, if ON active then paste else error
        if WinActive(winTitlePart)
        {
            Send("^v`r`r") ; Use sendplay to avoid unexpected interactions with Win key
            ; Switch window back to previously active
            WinActivate(actWin)
        }
        Sleep(500)
    }
    Else
    {
        MsgBox("Window < `"" winTitlePart "`" > does not Exist!")
    }
    A_Clipboard := OldClipboard
return
} ; V1toV2: Added Bracket before hotkey or Hotstring

^#+z:: ;Ctrl+win+shift+z tag a window as a copy destination
    ; Click, %A_CaretX%, %A_CaretY%
{ ; V1toV2: Added bracket
	Global
    MouseGetPos(, , &WinTag, &Control)
    winTitlePart := WinGetTitle("ahk_id " WinTag)
    MsgBox("`" " winTitlePart " `" is tagged as the destination window!`r - Press < Alt+Shift+C > to copy selection to this app.`r - Press < Ctrl+Win+Shift+R > to reset.", "Capsy CopyToApp", "")
return
} ; V1toV2: Added Bracket before hotkey or Hotstring

^#+r:: ;Ctrl+win+shift+r tag a window as a reset destination
{ ; V1toV2: Added bracket
	Global
    WinActivate("ahk_id " WinTag)
    MsgBox("CopyToApp windows is reset!", "Capsy CopyToApp", "T3")
    WinTag:=""
return
} ; V1toV2: Added bracket in the end
pgeugene
Posts: 40
Joined: 27 Jun 2019, 04:36

Re: Newly converted script not working

18 Feb 2024, 06:10

Hi,
Thank you for your solution.
It is working properly on Notepad, Text Editor Pro, Notepad++
Unfortunately it is not working on VSCode portable version..It was totally blank content
There was no text being pasted when I tried with VSCode
pgeugene
Posts: 40
Joined: 27 Jun 2019, 04:36

Re: Newly converted script not working

19 Feb 2024, 02:58

niCode wrote:
17 Feb 2024, 05:03
[Mod edit: Removed very long quote contents. Please use quotes more selectively.]

Thank you for your lengthy explaination.I have benefitted from it.My knowledge about AHK variable has improved a lot
pgeugene
Posts: 40
Joined: 27 Jun 2019, 04:36

Re: Newly converted script not working

19 Feb 2024, 03:19

Rohwedder wrote:
17 Feb 2024, 05:04
Hallo,
(untested), try:

Code: Select all

#Requires AutoHotkey v2.0
Global WinTag := winTitlePart := ""
+!c::  ; alt+shift+c to copy to the selected window

{ ; V1toV2: Added bracket
	Global
    If !WinTag
    {
        MsgBox("You pressed the combination of CopyToApp. First, tag a target window in NotePad        , WordPad or a GUI edit field.`r`r 1        . Activate window`n 2        . Press Ctrl+Win+Shift+Z", "Capsy CopyToApp", "")
        return
    }

    OldClipboard:= ClipboardAll()
    ; Clipboard:= ""
    Sleep(500)
    Send("^c") ;copies selected text
    Errorlevel := !ClipWait(1)
    If ErrorLevel
    {
        MsgBox("No text selected!", "Capsy CopyToApp", "")
        return
    }
    if WinExist(winTitlePart)
    {
        ;Save the currently active window title
        actWin := WinGetTitle("A")

        ; If OneNote is not active, activate it now
        if !WinActive(winTitlePart)
            WinActivate(winTitlePart)

        ; Check again, if ON active then paste else error
        if WinActive(winTitlePart)
        {
            Send("^v`r`r") ; Use sendplay to avoid unexpected interactions with Win key
            ; Switch window back to previously active
            WinActivate(actWin)
        }
        Sleep(500)
    }
    Else
    {
        MsgBox("Window < `"" winTitlePart "`" > does not Exist!")
    }
    A_Clipboard := OldClipboard
return
} ; V1toV2: Added Bracket before hotkey or Hotstring

^#+z:: ;Ctrl+win+shift+z tag a window as a copy destination
    ; Click, %A_CaretX%, %A_CaretY%
{ ; V1toV2: Added bracket
	Global
    MouseGetPos(, , &WinTag, &Control)
    winTitlePart := WinGetTitle("ahk_id " WinTag)
    MsgBox("`" " winTitlePart " `" is tagged as the destination window!`r - Press < Alt+Shift+C > to copy selection to this app.`r - Press < Ctrl+Win+Shift+R > to reset.", "Capsy CopyToApp", "")
return
} ; V1toV2: Added Bracket before hotkey or Hotstring

^#+r:: ;Ctrl+win+shift+r tag a window as a reset destination
{ ; V1toV2: Added bracket
	Global
    WinActivate("ahk_id " WinTag)
    MsgBox("CopyToApp windows is reset!", "Capsy CopyToApp", "T3")
    WinTag:=""
return
} ; V1toV2: Added bracket in the end
Hi, @Rohwedder
Thank you for your solution.
It is working properly on Notepad, Text Editor Pro, Notepad++
Unfortunately it is not working on VSCode portable version..It was totally blank content
There was no text being pasted when I tried with VSCode
Rohwedder
Posts: 7774
Joined: 04 Jun 2014, 08:33
Location: Germany

Re: Newly converted script not working

19 Feb 2024, 04:11

I don't use VSCode. Perhaps the script needs admin rights?
Try:

Code: Select all

#Requires AutoHotkey v2.0
#SingleInstance Force
if !(A_IsAdmin or RegExMatch(DllCall("GetCommandLine", "str"), " /restart(?!\S)"))
	try A_IsCompiled?Run('*RunAs "' A_ScriptFullPath '" /restart')
	:Run('*RunAs "' A_AhkPath '" /restart "' A_ScriptFullPath '"')
Global WinTag := winTitlePart := ""
+!c::  ; alt+shift+c to copy to the selected window

{ ; V1toV2: Added bracket
	Global
    If !WinTag
    {
        MsgBox("You pressed the combination of CopyToApp. First, tag a target window in NotePad        , WordPad or a GUI edit field.`r`r 1        . Activate window`n 2        . Press Ctrl+Win+Shift+Z", "Capsy CopyToApp", "")
        return
    }

    OldClipboard:= ClipboardAll()
    ; Clipboard:= ""
    Sleep(500)
    Send("^c") ;copies selected text
    Errorlevel := !ClipWait(1)
    If ErrorLevel
    {
        MsgBox("No text selected!", "Capsy CopyToApp", "")
        return
    }
    if WinExist(winTitlePart)
    {
        ;Save the currently active window title
        actWin := WinGetTitle("A")

        ; If OneNote is not active, activate it now
        if !WinActive(winTitlePart)
            WinActivate(winTitlePart)

        ; Check again, if ON active then paste else error
        if WinActive(winTitlePart)
        {
            Send("^v`r`r") ; Use sendplay to avoid unexpected interactions with Win key
            ; Switch window back to previously active
            WinActivate(actWin)
        }
        Sleep(500)
    }
    Else
    {
        MsgBox("Window < `"" winTitlePart "`" > does not Exist!")
    }
    A_Clipboard := OldClipboard
return
} ; V1toV2: Added Bracket before hotkey or Hotstring

^#+z:: ;Ctrl+win+shift+z tag a window as a copy destination
    ; Click, %A_CaretX%, %A_CaretY%
{ ; V1toV2: Added bracket
	Global
    MouseGetPos(, , &WinTag, &Control)
    winTitlePart := WinGetTitle("ahk_id " WinTag)
    MsgBox("`" " winTitlePart " `" is tagged as the destination window!`r - Press < Alt+Shift+C > to copy selection to this app.`r - Press < Ctrl+Win+Shift+R > to reset.", "Capsy CopyToApp", "")
return
} ; V1toV2: Added Bracket before hotkey or Hotstring

^#+r:: ;Ctrl+win+shift+r tag a window as a reset destination
{ ; V1toV2: Added bracket
	Global
    WinActivate("ahk_id " WinTag)
    MsgBox("CopyToApp windows is reset!", "Capsy CopyToApp", "T3")
    WinTag:=""
return
} ; V1toV2: Added bracket in the end
pgeugene
Posts: 40
Joined: 27 Jun 2019, 04:36

Re: Newly converted script not working

20 Feb 2024, 01:30

Rohwedder wrote:
19 Feb 2024, 04:11
I don't use VSCode. Perhaps the script needs admin rights?
Try:

Code: Select all

#Requires AutoHotkey v2.0
#SingleInstance Force
if !(A_IsAdmin or RegExMatch(DllCall("GetCommandLine", "str"), " /restart(?!\S)"))
	try A_IsCompiled?Run('*RunAs "' A_ScriptFullPath '" /restart')
	:Run('*RunAs "' A_AhkPath '" /restart "' A_ScriptFullPath '"')
Global WinTag := winTitlePart := ""
+!c::  ; alt+shift+c to copy to the selected window

{ ; V1toV2: Added bracket
	Global
    If !WinTag
    {
        MsgBox("You pressed the combination of CopyToApp. First, tag a target window in NotePad        , WordPad or a GUI edit field.`r`r 1        . Activate window`n 2        . Press Ctrl+Win+Shift+Z", "Capsy CopyToApp", "")
        return
    }

    OldClipboard:= ClipboardAll()
    ; Clipboard:= ""
    Sleep(500)
    Send("^c") ;copies selected text
    Errorlevel := !ClipWait(1)
    If ErrorLevel
    {
        MsgBox("No text selected!", "Capsy CopyToApp", "")
        return
    }
    if WinExist(winTitlePart)
    {
        ;Save the currently active window title
        actWin := WinGetTitle("A")

        ; If OneNote is not active, activate it now
        if !WinActive(winTitlePart)
            WinActivate(winTitlePart)

        ; Check again, if ON active then paste else error
        if WinActive(winTitlePart)
        {
            Send("^v`r`r") ; Use sendplay to avoid unexpected interactions with Win key
            ; Switch window back to previously active
            WinActivate(actWin)
        }
        Sleep(500)
    }
    Else
    {
        MsgBox("Window < `"" winTitlePart "`" > does not Exist!")
    }
    A_Clipboard := OldClipboard
return
} ; V1toV2: Added Bracket before hotkey or Hotstring

^#+z:: ;Ctrl+win+shift+z tag a window as a copy destination
    ; Click, %A_CaretX%, %A_CaretY%
{ ; V1toV2: Added bracket
	Global
    MouseGetPos(, , &WinTag, &Control)
    winTitlePart := WinGetTitle("ahk_id " WinTag)
    MsgBox("`" " winTitlePart " `" is tagged as the destination window!`r - Press < Alt+Shift+C > to copy selection to this app.`r - Press < Ctrl+Win+Shift+R > to reset.", "Capsy CopyToApp", "")
return
} ; V1toV2: Added Bracket before hotkey or Hotstring

^#+r:: ;Ctrl+win+shift+r tag a window as a reset destination
{ ; V1toV2: Added bracket
	Global
    WinActivate("ahk_id " WinTag)
    MsgBox("CopyToApp windows is reset!", "Capsy CopyToApp", "T3")
    WinTag:=""
return
} ; V1toV2: Added bracket in the end
Thank you for your new suggestion.
Still not working even tried your susgested admin rights.
I removed/reinstalled VSCode portable version also same.
I also Disabled all extentions...same result

Return to “Ask for Help (v2)”

Who is online

Users browsing this forum: AccelAHK, Draken and 41 guests