I tried to write a ahk script which allows me to bind the currently opened window to a hotkey. The way it works is that if you press ALTGR + , + any character, the ProcessPath of the current window gets saved.
Now, using ALTGR + the choosen character, i either switch to this window if its already opened (Activate) or run the .exe file for this process.
To delete the hotkey i use ALTGR + . + respective key.
All hotkeys get saved in an .ini file so the settings don't get lost.
It all works fine..... but the thing is: I had to copy the code for every key (i wrote a python script to copy it for me). Is there a way to set dynamic hotkeys in ahk?
Here is my code:
iniFile := "winshortcut.ini"
Runs a certain process or switches to the window if already running. The loop works around some delays that might occur.
RunOrActivate(key, Target)
{
SplitPath, Target, TargetNameOnly, , TargetEXE
Process, Exist, %TargetNameOnly%
If (ErrorLevel > 0){
WinActivate, ahk_pid %ErrorLevel%
} else {
if (Target != "ERROR") {
Run, %Target%
if (TargetEXE != "exe"){
WinGetTitle, x, A
if (x != TargetNameOnly){
Loop, 5 {
Sleep, 100
Run, %Target%
}
}
}
} else {
TrayTip AltGr+%key%, No binding, 2
}
}
}
This line reads the path for a key from the ini file. I had to copy it for every single key:
IniRead, PATH_w, %iniFile%, savedKeys, w
IniRead, PATH_r, %iniFile%, savedKeys, r
...
This block handles the hotkeys for saving, deleting or changing the process for a single key (w). This is copied and changed 23 times:
; ############## w ##############
<^>!w::
if (GetKeyState(",")){
if (PATH_w != "ERROR") {
SplitPath, PATH_w, TITLE_w_old
}
WinGet PATH_w, ProcessPath, A
SplitPath, PATH_w, TITLE_w
if (TITLE_w == "Explorer.EXE"){
WinGetTitle, TITLE_w, A
for w in ComObjCreate("Shell.Application").Windows
if (TITLE_w = w.Document.Folder.Self.Name) {
PATH_w := % w.Document.Folder.Self.Path
}
}
IniWrite, %PATH_w%, %iniFile%, savedKeys, w
if (TITLE_w_old) {
if (TITLE_w_old != TITLE_w){
TrayTip Changing binding for AltGr+W, From %TITLE_w_old% to %TITLE_w%
} else {
TrayTip Binding for AltGr+W, %TITLE_w%
}
} else{
TrayTip New binding for AltGr+W, %TITLE_w%
}
} else if (GetKeyState(".")){
PATH_w := "ERROR"
TITLE_w_old := ""
IniDelete, %iniFile%, savedKeys, w
TrayTip AltGr+W, Binding deleted
} else {
RunOrActivate("W", PATH_w)
}
return
Is there a way in ahk to pack hotkeys into a single function?
Here is the whole thing including the python code i wrapped around:
A_ThisHotkey
. – zwer