简体   繁体   中英

Changing focus with Autohotkey, what is going on?

I just want my script to select the right Window to input key storkes. To do this I think I use WinActivate. I ran the example from their site but found some strange results in Windows 10

IfWinExist, Untitled - Notepad
    WinActivate ; use the window found above
else
    WinActivate, Calculator;
  1. If Notepad is minimized, it gets the focus
  2. If Notepad is open but is not have the focus (ie another window is on top of it), Notepad gets the focus
  3. If Notepad is not open and the calculator is minimized, for some strange reason it doesn't get the focus.
  4. If Notepad is not open and the calculator is open but not have the focus, it gets the focus.

What is causing the inconsistency?

It happens because of the implementation of the WinActivate function on the language. WinActivate tries to open an window, but it might not be able to. From the documentation

Six attempts will be made to activate the target window over the course of 60ms. Thus, it is usually unnecessary to follow WinActivate with WinWaitActive or IfWinNotActive.

Usually you can try the #WinActivateForce directive in combination with WinWaitActive or IfWinNotActive .

Sometimes you can use an ahk_exe parameter to match the window. It may work in cases where the window title doesn't. In this case you would use

Also it's useful to try restoring the window with WinRestore .

SetTitleMatchMode, 2
IfWinExist, Bloco de notas
{
    WinActivate ; use the window found above
}
else
{
    WinRestore, ahk_exe calc.exe    
    WinActivate, ahk_exe calc.exe
}

I'm on Win7, but the above worked for me.

Here is an example of a good and complete implementation of a function that tries to activate a window.

Semicolons introduce comments in AHK. There has to be a white space before it, otherwise it's seen as part of the string (alias winactivate "Calculator;")

so, use

WinActivate, Calculator ;

or just omit the ; , for it doesn't contribute anything

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM