How to start a program if not already started, put on focus if already started? - autohotkey

I would like to make a ahk script to start apps if they are not currently started and maximize them if they are. Is it possible using AHK ?
CapsLock & w::
Run firefox.exe
Return
Something like this but make it so that if I press CapsLock & w and then minimize firefox, pressing CapsLock & w would bring it back maximized / in focus. Any ideas? Thanks!

Sure, this is very easy and doable with AHK.
Here's a very easy and straight forward example
CapsLock & w::
if (WinExist("ahk_exe notepad.exe"))
{
WinActivate, ahk_exe notepad.exe
WinMaximize, ahk_exe notepad.exe
}
else
Run, notepad.exe
return
ahk_exe (docs) is used to refer to windows by their process. It's very convenient.

The code that you are looking for is somewhat similar to the example they give in the docs for WinActivate
So modifying that example for your purpose, and adding conditionals would give you:
CapsLock & w::
if WinExist("ahk_exe firefox.exe")
if WinActive("ahk_exe firefox.exe")
WinMinimize
else
WinActivate
else
Run firefox.exe
Return
Take note that this script will currently only minimize a Firefox window if it is the currently active window. If you need it to minimize a Firefox in the background, the script would potentially be a bit more complex since you could possibly have multiple Firefox windows open, and you would need to provide conditions and logic to handle cases like those. However, if you need this functionality, describe what behavior you would like to occur if this condition occurs, and I can work on it.

Related

AutoHotKey WinActive returns wrong value when changing window focus

In my AutoHotKey script I'm using #IfWinActive to detect if the Roblox window is in focus, and then press the number 1 button whenever left clicking the mouse, like this:
#IfWinActive, Roblox
LButton::
MouseClick, Left
SendInput, {1}
return
#IfWinActive
It works great, except for when I'm clicking out of the Roblox window back to another window. It still fires this code on the first click, resulting in it typing the number 1 into Notepad (or whatever window I switch focus to).
I figured that when I'm clicking on Notepad the focus is still on the Roblox window, which is why the code still fires. So I tried changing the code to this:
#IfWinActive, Roblox
LButton::
Sleep, 100
if WinActive("Roblox")
{
MouseClick, Left
SendInput, {1}
}
return
#IfWinActive
Assuming that by the time the Sleep finished the focus would have shifted to the Notepad window and If WinActive("Roblox") would return false, but it still returns true and types 1 into Notepad.
I also tried using StartTimer and a label, thinking that maybe the Sleep wasn't asynchronous, but that has the same problem as well.
Anybody know how to get around this issue? Thanks in advance!
The main problem in this case is that the hotkey is fired immediately after LButton is pressed down and the Roblox window is still active.
The only solution I see is to fire the hotkey upon release of the LButton using the tilde prefix (~) to prevent AHK from blocking the key-down/up events:
#IfWinActive, Roblox
~LButton Up:: SendInput, 1
#IfWinActive
There are a couple of ways we can achieve this. TL;DR for solution, check the yellow part of this post.
Firstly I'll address the problems in your code:
Usage of MouseClick over Click. Technically nothing wrong, but Click is said to be more reliable in some situations and easier to use. Looks cleaner as well.
Wrapping 1 in {} is not needed and does nothing for you here. In some cases you may even produce unwanted behavior by doing this. In a send command, {} is used to escape keys that have special meaning, or to define keys that you can't just type in. More about this from the documentation.
Having a somewhat of a bad WinTitle that you're matching against. Again, nothing technically wrong, but right now you match any window that starts with the word Roblox. Shouldn't be too hard accidentally match the wrong window.
A quick and a very effective solution would be matching against the process name of your Roblox window.
So #IfWinActive, ahk_exe Roblox.exe or in an if-statement if (WinActive("ahk_exe Roblox.exe")) (assuming that's the process' name, I have no idea)
For an absolutely fool proof way could match against the hwnd of the Roblox window. However, that's maybe a bit overkill and you couldn't really use it with #IfWinActive either. An example I'll write below will use this that though.
However, problems 1 and 2 can be entirely avoided by doing this neat way of remapping a key (remapping is pretty much what you're doing here).
~LButton::1
Ok, so why does that work?
key::key is just the syntax to easily do a basic remap, and with ~ we specify that the hotkey isn't consumed when it fires.
Cool, but now onto the actual problem you're having.
So what went wrong with the sleeping thing? Well since you're consuming the hotkey, all you're actually doing is firing the hotkey, waiting 100ms, then checking if Roblox is active. Well yes, it will still be active since nothing was ever done to switch focus away from it.
If you were to not consume the left clicking action, it would work, but it's definitely not a good idea. You do not want to sleep inside a hotkey statement. AHK does not have true multithreading and unless you would've specified a higher #MaxThreadsPerHotkey for your hotkey, all subsequent presses of the hotkey would be totally ignored for that 100ms.
So yes, with specifying a higher amount of threads that can run for that hotkey, it would kind of make this solution work, but it's still bad practice. We can come up with something better.
With timers you can avoid sleeping in the hotkey statement. Sounds like you tried the timers already, but I can't be sure it went right since code wasn't provided so I'll go over it:
#IfWinActive, ahk_exe Roblox.exe
~LButton::SetTimer, OurTimersCallbackLabel, -100 ;-100 specifies that it runs ONCE after 100ms has passed
#IfWinActive
OurTimersCallbackLabel:
if (WinActive("ahk_exe Roblox.exe"))
SendInput, 1
return
And now onto the real solution, to which #user3419297 seems to have beat me to, just as I'm writing this line of text.
Using the up event of your LButton press as the hotkey.
#IfWinActive, ahk_exe Roblox.exe
~LButton Up::SendInput, 1
#IfWinActive
This way the down event has already switched focus of the window and our hotkey wont even fire.
Note that here we unfortunately can't use the key::key way of remapping I described above.
Bonus:
Here's something that could be used if the up event of our keypress wouldn't be desirable, or somehow the window switching of the active window was delayed.
RobloxHwnd := WinExist("ahk_exe Roblox.exe")
#If, RobloxUnderMouse()
~LButton::1
#If
RobloxUnderMouse()
{
global RobloxHwnd ;specify that we're using the variable defined outside of this function scope
;could've also ran the code to get Roblox's hwnd here every time, but that would be wasteful
MouseGetPos, , , HwndUnderMouse ;we don't need the first two parameters
return RobloxHwnd == HwndUnderMouse ;are they the same hwnd? (return true or false)
}
Here we're first storing the hwnd of our Roblox to the variable RobloxHwnd.
Note that Roblox would need to be running before we run this script, and if you restart robox, script would need to be restarted as well.
So adding some way of updating the value of this variable on the fly would be good, maybe under some hotkey.
Then by using #If we're evaluating an expression (in our case, running a function and evaluating its return value) every time we're about to attempt to fire the hotkey. If the expression evaluates to true, we fire the hotkey.
Usage of #If is actually not recommended, and it is good practice to avoid using if at all possible. However, you wont encounter any problems in a script this small, so using #If is going to be very convenient here.
If you were to have a bigger script in which there's a lot of code running often, you'd be likely to run into problems.

How to find OneNote windows 10 in AutoHotKey's if winexist?

I'm trying to build a script that allows me to open and use OneNote (The store app not OneNote 2016) with a hotkey, but I would like to use the same hotkey to switch the the app from another window. I have accomplished this with many other programs, but never with windows store app. Here is the code I'm trying to use.
#If WinExist("OneNote ahk_class ApplicationFrameWindow", "OneNote")
{
WinActivate,
}
Else
Run, C:\Users\ChrisCochrun\Documents\OneNote
#If
Unfortunately it's not detecting that the window exists and it'll only just launch a new instance of onenote. I've looked for answers, but I'm having trouble making it so that AHK actually sees the window already running and jumping to it.
Thanks very much for any help at all!
If the window's title doesn't start with "OneNote", you need to use
SetTitleMatchMode 2.
The #If-directive is only used for creating context-sensitive hotkeys and hotstrings.
F1:: ; or a hotkey of your choise
SetTitleMatchMode 2
If WinExist("OneNote ahk_class ApplicationFrameWindow", "OneNote")
WinActivate
Else
Run, C:\Users\ChrisCochrun\Documents\OneNote
return
rshfit::
SetTitleMatchMode 2
If WinExist("OneNote for Windows 10")
WinActivate return
;If I use rshift to activate Onenote for Windows 10

Ableton Issue while trying to control click

Even though I have read the docs and watched tutorials I am a complete beginner so I apologize If its a silly question. I have tried for quite a while to do this with no results.
I want to have NUMPAD0 key to press the global recording button in Ableton Live but I do not want to do it through mouse coordinates (1. Because the windows might be minimized when I need to record and 2. Because I want to implement this in the future in order to be able to press the recording button also on individual tracks as I create them, which might range from 1 to 80 new tracks for example)
The thing is that the Windows class dynamically changes and the Control ID is not shown in winspy.
This is what I have been doing:
GroupAdd, Live, ahk_class
Afx:0000000140000000:0:0000000000000000:0000000000900015:00000000007A04C3
GroupAdd, Live, ahk_class
Afx:0000000140000000:0:0000000000000000:0000000000900015:0000000000200651
GroupAdd, Live, ahk_class
Afx:0000000140000000:0:0000000000000000:0000000000900015:0000000000290651
GroupAdd, Live, ahk_class
Afx:0000000140000000:0:0000000000000000:0000000000900015:00000000001E05F1
curMode := 1
return
Numpad0::
SetControlDelay -1
controlclick, ahk_group Live0,,,,,NA
return
So, my issues are these: 1. In the GroupAdd command I have put the window classes that I have seen yet I believe there might be more classes, that appear everytime I open a new Ableton window. 2. In the Control Click command, I havent put the control ID because I couldnt find it.
Any advice on how to finish this code or change it to a different it in order to press that Record button in Ableton, without using coordinates?
EDIT:
This is the code Im trying now, following suggestions but I havent got any results yet:
SetTitleMatchMode, Regex
SetTitleMatchMode, Slow
#IfWinActive, .*als
Numpad0::F9
#IfWinActive
return
And this is the 2 version of that, which is not working either
SetTitleMatchMode, Regex
SetTitleMatchMode, Slow
#IfWinActive, Afx:0000000140000000
Numpad0::F9
#IfWinActive
return
While I've never used GroupAdd, if there's a finite number of Class permutations, it seems to me you could RegExMatch against those and then form your group inside that. The GroupAdd spec seems to make all parameters optional beyond the GroupName, so perhaps you could skip the Class declaration after confirming you've got the right window.
Example:
WinGetTitle, Title, A
WinGetClass, Class, A
if (RegExMatch(Title, "Ableton Live.*") AND (RegExMatch(Class, "(AbletonClass1|AbletonClass2|AbletonClass3)")))
{
; Do stuff
}

Autohotkey autocomplete limit to certain windows

I am trying to use the Autohotkey autocomplete script here: http://www.autohotkey.com/board/topic/60998-autocomplete-updated-26713/ but limit it to certain windows. Enclosing the entire script within #IfWinActive does not seem to work. I really like this completion script but would not want it showing up all over the place. Is there a way to limit the autocompletion to specific windows?
A quick study of the source code showed that every keypress results in a call of the Suggest subroutine. This seems to be a good place to check for the active window. I've implemented a minimal change in the source, you can check it out here.
First, you have to define which windows you want to exlude from the functionality, I achieved this by defining a window group:
GroupAdd, excludedWins, ahk_class CabinetWClass ; windows explorer
GroupAdd, excludedWins, ahk_class DV2ControlHost ; start menu search bar
GroupAdd, excludedWins, ahk_class ConsoleWindowClass ; console
Please note that I'm using Windows 7; maybe, the windows have other identifiers in other versions.
Second, you need to tell the Suggest subroutine to ignore these windows:
Suggest:
IfWinActive, ahk_group excludedWins
{
return
}
It seems to work, but I only tested very superficially and didn't investigate the source code dependencies. Let me know how it works for you.

How can I make AutoHotkeys's functions stop working as soon as the .exe is closed?

I'm testing AutoHotkeys as a way to block user's usage of Ctrl, Alt and Windows Key while an application is running. To do this, I compiled the code:
LAlt::return
RAlt::return
LControl::return
RControl::return
RWin::Return
LWin::Return
into an .exe using the compiler that comes with AutoHotkeys.
My problem is that normally when I close the .exe file (either by code using TerminateProcess(,) or manually) the keys are not released immediately. The Windows Key, for example, may take something like 10 seconds to be finely "unlocked" and become able to be used again, and for me this is unacceptable.
So I got two questions:
Is there a way to fix this problem? How can I make the keys to be released as soon as the .exe is closed?
Would there be any improvement if I tryed to get the same functionality by code? Or if I create the hooks by myself I would get the same problem I'm having with AutoHotkeys?
Thanks,
Momergil
AutoHotkey has a built-in command ExitApp for terminating your scripts.
This example makes Esc your termination hotkey:
Esc::ExitApp
It seems like the delay you are experiencing might be related to how long it's taking the process to close.
You could try making the hotkeys conditional with the #If command*
(i.e. they are only blocked when Flag = 1).
Then you can have the script quickly change the context just before ExitApp by using OnExit. The OnExit subroutine is called when the script exits by any means (except when it is killed by something like "End Task"). You can call a subroutine with a hotkey by using the GoSub command.
Flag := 1
OnExit, myExit
Esc::GoSub, myExit
#If Flag
LAlt::return
LCtrl::return
x::return
#If
myExit:
Flag := 0
Exitapp
* The #If command requires Autohotkey_L.
The other option that will be more verbose, but work for AHK basic, is the hotkey command.
Another option is to have AutoHotkey run the target application, and upon application exit, AutoHotkey exits as well. Here's an example with Notepad. When the user closes Notepad, the script gracefully exits.
RunWait, Notepad.exe
ExitApp ; Run after Notepad.exe closes
LAlt::return
RAlt::return
LControl::return
RControl::return
RWin::Return
LWin::Return
I would use winactive to disable these keys. In this example the modyfier keys are disabled for "Evernote". As soon as you switch to another program the keys are restored and when you switch back to Evernote the modifier keys are disabled again.
SetTitleMatchMode, 2 ; Find the string Evernote anywhere in the windows title
#ifWinActive Evernote
LAlt::return
RAlt::return
LControl::return
RControl::return
RWin::Return
LWin::Return
#ifWinActive