Autohotkey Application Keycounter - counter

I am trying to create an application based Key counter. Below is my script
#UseHook
KeyCount=0
#If WinActive("Ahk_Class XLMAIN") Or WinActive("Ahk_Class Notepad")
Loop
{
Input, Key, L1 I V, ,
AscKey:=Asc(Key)
If (AscKey > 31 && AscKey < 127)
KeyCount:=KeyCount+1
}
#If
^+o::
msgbox %KeyCount%
return
As the WinActive commands says it should count keystrokes if active window is either Excel or notepad. But this script counts all keystrokes. Am I missing something?

You don't use the #if its only for hotkeys and hotstrings but you can use a normal if statment like this
#UseHook
KeyCount=0
Loop
{
Input, Key, L1 I V
If (WinActive("Ahk_Class XLMAIN") Or WinActive("Ahk_Class Notepad"))
{
AscKey:=Asc(Key)
If (AscKey > 31 && AscKey < 127)
KeyCount++
}
}
^+o::
msgbox %KeyCount%
return
Hope it helps

Related

Script in AutoHotkey to Press Windows button and Left Arrow simultaneously

I want to write a script in autohotkey so that every time I open my dictionary application on PC, keys Windows+LeftArrow being pressed at the same time and as the result, it snaps the windows on the left side of monitor.
I tried this:
#IfWinActive Oxford Advanced Learner's Dictionary
Send, #{Left}
return
Also this one:
#IfWinActive Oxford Advanced Learner's Dictionary
Send, {LWinDown}{Left}{LWinup}
return
But for either of them noting happened when I opened the application.
EDIT:
As suggested by #Charlie Armstrong the real question is: How do I make a block of code run every time I start a certain program? So #IfWinActive might not be useful for.
One way is periodically check if new process/window is created and to check if that is a process/window we want to interact with.
This first example is based on COM notifications when a process has been created/destroyed.
; help for question: https://stackoverflow.com/q/66394326/883015
; by joedf (16:04 2021/02/28)
MyWatchedWindowTitle := "Oxford Advanced Learner's Dictionary"
NewProcess_CheckInterval := 1 ; in seconds
SetTitleMatchMode, 2 ;this might not be needed, makes the check for "contains" instead of "same" winTitle
hWnds := []
gosub, initialize_NewProcessNotification
return
; Called when a new process is detected
On_NewProcess(proc) {
global hWnds
global MyWatchedWindowTitle
; get the window handle, if possible
if (hwnd:=WinExist("ahk_pid " proc.ProcessID)) {
WinGetTitle, wTitle, ahk_id %hwnd%
; check if there is a visible window
if (wTitle)
{
; if so, check if it's a window we want to interact with
if (InStr(wTitle,MyWatchedWindowTitle))
{
; check if we've interacted with this specific window before
if (!ArrayContains(hWnds, hwnd)) {
; we havent, so we do something with it
hWnds.push(hwnd) ; keep in memory that we have interacted with this window ID before.
DoSomething(hwnd) ; the keys we want to send to it
}
}
}
}
}
DoSomething(hwnd) {
; size and move window to the left
SysGet, MonitorWorkArea, MonitorWorkArea
posY := 0
posX := 0
width := A_ScreenWidth // 2
height := MonitorWorkAreaBottom
WinMove, ahk_id %hwnd% ,,%posX%,%posY%,%width%,%height%
; multi-montitor support, more examples, and more complete snapping functions can be found here:
; https://gist.github.com/AWMooreCO/1ef708055a11862ca9dc
}
ArrayContains(haystack, needle) {
for k, v in haystack
{
if (v == needle)
return true
}
return false
}
initialize_NewProcessNotification:
;////////////////////////////// New Process notificaton ////////////////////////
; from Lexikos' example
; https://autohotkey.com/board/topic/56984-new-process-notifier/#entry358038
; Get WMI service object.
winmgmts := ComObjGet("winmgmts:")
; Create sink objects for receiving event noficiations.
ComObjConnect(createSink := ComObjCreate("WbemScripting.SWbemSink"), "ProcessCreate_")
ComObjConnect(deleteSink := ComObjCreate("WbemScripting.SWbemSink"), "ProcessDelete_")
; Set event polling interval, in seconds.
interval := NewProcess_CheckInterval
; Register for process creation notifications:
winmgmts.ExecNotificationQueryAsync(createSink
, "Select * from __InstanceCreationEvent"
. " within " interval
. " where TargetInstance isa 'Win32_Process'")
; Register for process deletion notifications:
winmgmts.ExecNotificationQueryAsync(deleteSink
, "Select * from __InstanceDeletionEvent"
. " within " interval
. " where TargetInstance isa 'Win32_Process'")
; Don't exit automatically.
#Persistent
return
; Called when a new process is detected:
ProcessCreate_OnObjectReady(obj) {
proc := obj.TargetInstance
/*
TrayTip New Process Detected, % "
(LTrim
ID:`t" proc.ProcessID "
Parent:`t" proc.ParentProcessID "
Name:`t" proc.Name "
Path:`t" proc.ExecutablePath "
Command line (requires XP or later):
" proc.CommandLine
)
*/
On_NewProcess(proc)
}
; Called when a process terminates:
ProcessDelete_OnObjectReady(prm) {
/*
obj := COM_DispGetParam(prm, 0, 9)
proc := COM_Invoke(obj, "TargetInstance")
COM_Release(obj)
TrayTip Process Terminated, % "
(LTrim
ID:`t" COM_Invoke(proc, "Handle") "
Name:`t" COM_Invoke(proc, "Name")
)
COM_Release(proc)
*/
}
This second example, which is perhaps a bit simpler, checks periodically for new windows that match the searched WinTitle.
; help for question: https://stackoverflow.com/q/66394326/883015
; by joedf (16:17 2021/02/28)
#Persistent
MyWatchedWindowTitle := "Oxford Advanced Learner's Dictionary"
SetTitleMatchMode, 2 ;this might not be needed, makes the check for "contains" instead of "same" winTitle
SetTimer, checkForNewWindow, 1000 ;ms
hWnds := []
return
checkForNewWindow() {
global hWnds
global MyWatchedWindowTitle
; first check if there is at least one window that matches our winTitle
if (hwnd:=WinExist(MyWatchedWindowTitle)) {
; get all window matches
WinGet, wArray, List , %MyWatchedWindowTitle%
; loop through all windows that matched
loop % wArray
{
hWnd := wArray%A_Index%
; check if we've interacted with this specific window before
if (!ArrayContains(hWnds, hwnd)) {
; we havent, so we do something with it
hWnds.push(hwnd) ; keep in memory that we have interacted with this window ID before.
DoSomething(hwnd) ; the keys we want to send to it
}
}
}
}
DoSomething(hwnd) {
; size and move window to the left
SysGet, MonitorWorkArea, MonitorWorkArea
posY := 0
posX := 0
width := A_ScreenWidth // 2
height := MonitorWorkAreaBottom
WinMove, ahk_id %hwnd% ,,%posX%,%posY%,%width%,%height%
; multi-montitor support, more examples, and more complete snapping functions can be found here:
; https://gist.github.com/AWMooreCO/1ef708055a11862ca9dc
}
ArrayContains(haystack, needle) {
for k, v in haystack
{
if (v == needle)
return true
}
return false
}
I think your biggest issue is that AHK doesn't seem to work well for snapping windows (according to my quick research and testing). What does work well, though, is WinMove.
I assume you're launching the program from a shortcut icon, but I would suggest using a keyboard shortcut that launches the program and then positions the window from the script. Here is some sample code that opens Notepad2.exe, waits for 200 milliseconds, and then moves the window and resizes it:
^+!n:: ; Control+Shift+Alt+N to Open Notepad
Run C:\Program Files\Notepad2\Notepad2.exe
sleep, 200
WinMove, Notepad2,, 10, 20, 800, 600
return

Hotkey to toggle another hotkey into a different function or mode

I'm trying to get a the hotkey LCTRL to toggle XButton2 into different modes.
The issue is that it's saying that there are duplicate hotkeys in the same script. I clearly don't know what's going on. Help?
~LCtrl::
actioncameratoggle := !actioncameratoggle
if actioncameratoggle
{
~XButton2::
rTurn := !rTurn
if rTurn
{
send {lctrl}
mousemove, 800, 450
send {ctrl}
mousemove, 1600, 450
}
else
{
}
}
else
{
~XButton2::
{
}
}
return
Thanks!
With your Script You can not toggle with the same hotkeys, the reason is you want to use the if with the Else commands > if hotkey1:: else hotkey1::, you will need the #if commands. Look to this example code.
You can Write this example.ahk Code and try it out on your Windows System.
Change the code a little bit for your needs, and it is done.
I did make the script so that the other guys can simple test it out.
; [+ = Shift] [! = Alt] [^ = Ctrl] [# = Win]
a := 1
#If mode1 ; All hotkeys below this line will only work if mode1 is TRUE or 1
t::1
; Here you can put your first hotkey code ~XButton2::
#If
#If mode2 ; All hotkeys below this line will only work if mode2 is TRUE or 1
t::2
; And here you can put your second hotkey code ~XButton2::
#If
; toggle between [t::1] and [t::2]
;a = 1 => t::1
;a = 2 => t::2
;type LCtrl key to toggle between two the same hotkeys
;you can test it out in notepad - if you then type the key t
~LCtrl::
if (a=1)
{
mode1 = 1
mode2 = 0
a := 2
}else{
mode1 = 0
mode2 = 1
a := 1
}

How can I bind several keys to the same command in AutoHotKey?

How can I bind several keys to the same command in AutoHotKey?
Example: I have this command:
spamLimit(limitTime)
{
StringReplace, key, A_ThisHotkey, $, , All
send %key%
sleep limitTime
}
I would like to bind several to this command, with the same parameter value:
a::spamLimit(500)
b::spamLimit(500)
c::spamLimit(500)
p::spamLimit(500)
d::spamLimit(500)
e::spamLimit(500)
Simplest solution:
a::
b::
c::
p::
d::
e::
spamLimit(500)
return
You can use Hotkey to define hotkeys on the fly:
; Thanks engunneer: autohotkey.com/board/topic/45636-script-to-prevent-double-typing/?p=284048
; Thanks throwaway_ye: https://www.reddit.com/r/AutoHotkey/comments/54g40q/how_can_i_bind_several_keys_to_the_same_command/d81j0we
; The following part must be located in the auto-execute section,
; i.e. the top part of the AHK script.
keylist = 1234567890qwertzuiopasdfghjklyxcvbnm
Loop, parse, keylist
{
Hotkey, $%A_LoopField%, spamLimitNoParam
}
Return
; This can be located anywhere in the AHK file
spamLimitNoParam:
spamLimit(200)
Return
This is equivalent to the solution Bob pointed to:
$a::
$b::
$c::
$d::
$e::
$f::
$g::
$h::
$i::
$j::
$k::
$l::
$m::
$n::
$o::
$p::
$q::
$r::
$s::
$t::
$u::
$v::
$w::
$x::
$y::
$z::
$0::
$1::
$2::
$3::
$4::
$5::
$6::
$7::
$8::
$9::
spamLimit(200)

AHK: closing a window whenever it pops up

I wrote an AHK script designed to copy a text from Adobe Acrobat when I press F9. It then changes it according to a regex and shows the copied text in tooltip. Additionally, I added code to automatically close an annoying window that Acrobat sometimes shows when coping a text, an infamous There was an error while copying to Clipboard. An internal error occurred. When this window doesn't show up, the script keeps showing a tooltip, which is designed to close after a specified amount of time. I've been banging my head against the wall but I don't know how to correct this.
;#NoTrayIcon
#Persistent
#SingleInstance
F9::
#If WinActive("ahk_exe Acrobat.exe")
{
Clipboard:=""
send,^c
ClipWait, 1
Clipboard := RegExReplace(Clipboard, "\r\n", " ")
SetTimer,CheckForMsgBox,100
CheckForMsgBox:
IfWinExist, Adobe Acrobat
{
Send {Enter}
SetTimer,CheckForMsgBox,Off
}
;Return
If (StrLen(Clipboard) < 120)
ToolTip % Clipboard
Else
ToolTip Copied
SetTimer, ToolTipOff, -1000
return
}
#If
ToolTipOff:
ToolTip
return
;#NoTrayIcon
; #Persistent ; (1)
#SingleInstance
SetTimer,CheckForMsgBox,100 ; (2)
return
#If WinActive("ahk_exe Acrobat.exe") ; (3)
F9::
clipboard:=""
send,^c
ClipWait, 1
Clipboard := RegExReplace(Clipboard, "\r\n", " ")
If (StrLen(Clipboard) < 120)
ToolTip %Clipboard%
Else
ToolTip Copied
SetTimer, ToolTipOff, -1000
return
#If ; turn off context sensitivity
ToolTipOff:
ToolTip
return
CheckForMsgBox:
; ControlSend, Control, Keys, WinTitle, WinText, ExcludeTitle, ExcludeText
ControlSend, , {Enter}, Adobe Acrobat ; Close this unwanted window whenever it appears
return
(1) Scripts containing hotkeys, hotstrings, or any use of OnMessage() or Gui are automatically persistent.
(2) SetTimer causes a subroutine (Label) to be launched automatically and repeatedly at a specified time interval.
https://autohotkey.com/docs/commands/SetTimer.htm
(3) Like the #IfWin directives, #If is positional: it affects all hotkeys and hotstrings physically beneath it in the script.
https://autohotkey.com/docs/commands/_If.htm

Autohotkey script to bookmark to a specific folder

I'm using Firefox and I was looking for an autohotkey script which would enable me to skip the whole series of clicks when I bookmark a page in a specific folder and replace it with a single keyboard shortcut.
Although I've read forum threads on Autohotkey forum and here I still don't know how to make a working script that would reduce bookmarking a page to hitting a keyboard shortcut and the initial letter of the folder where I want to store that page. Using KeyWait command I've made it work for a single folder and don't know how to make it work for any letter or a number that I could possibly use as a name for a bookmark folder. Say I have a folder named XXXX, this script does send the webpage to the XXXX folder after hitting the assigned shortcut and the letter x (MouseClick command is needed to focus the window with folder in the Bookmark Dialog pane):
!+^w::
Send,^d
Sleep,400
MouseClick,Left,864,304
Sleep,400
KeyWait, x ,D
Sleep, 400
Send,^{Enter}
return
I don't know how to make this script work for any letter or number, not only for a single one. Also a big problem with this script is that it blocks the keyboard until I hit X key. If I have that page bookmarked already, hitting escape to remove the bookmark pane will block the keyboard and I can unblock it only if I rerun the autohotkey script.
I've also tried using Input command as the contributors the Autohotkey forum pages suggested, but it didn't work either, because I don't understand how the Input command works. I did make it work for a single letter as the above script with KeyWait, but that's the best I could do. This script also blocks the keyboard until the letter is hit:
!+^w::
Send,^d
MouseClick,Left,864,304
Sleep,400
Input, Character, L1
If Character = t
Send, t
Sleep,400
Send,^{Enter}
return
Hope someone can help me with this, it would be convenient simplifying the bookmarking process in Firefox this way.
I have a nice idea. This will open the add bookmark dialog and navigate you into the folder selection part and expand all folders.
All you need to do is enter the folders name (or a part of it) and it will get selected automatically. When you're done, just hit enter.
!+^w:: ;Hotkey: Ctrl+Alt+Shift+w
Send, ^d ;send Ctrl+d to open the add-bookmark dialog
Sleep, 500 ;wait for the dialog to open
Send, {Tab}{Tab}{Enter} ;navigate into the folder selection
Sleep, 300 ;wait to make sure we are there
Send,{Home} ;select the first item in the list
;The following line should expand all the folders so that you can just type the folders name to search for it
Loop, 100 { ;Increase the number if it doesn't expand all folders
SendInput, {Right}{Down} ;expand folders
}
Send, {Home} ;navigate to the first item in the list again
Input, L, V L1 T2 ;wait until you start typing a folder name (if you just wait 2 seconds, the bookmark won't be created)
If (ErrorLevel = "Timeout") {
Send, {Tab 5} ;press tab 5 times to navigate to the cancel button
Send, {Enter} ;cancel the bookmark
Return ;end of the hotkey
}
Loop { ;wait until you haven't typed a new letter for 0.4 seconds
Input, L, V L1 T0.4
If (ErrorLevel = "Timeout")
Break
}
Send, {Tab 4} ;press tab 4 times to navigate to the enter button
Send, {Enter} ;save the bookmark
Return
My variant.
Press f1 to create bookmark in folder test1.
Press f2 to create bookmark in folder test2.
SetBatchLines, -1
Folders := {F1: "test1", F2: "test2"}
#IfWinActive, ahk_class MozillaWindowClass
F1::
F2::
Folder := Folders[A_ThisHotkey]
Send, ^d
AccFirefox := Acc_ObjectFromWindow(WinExist("ahk_class MozillaWindowClass"))
AccElem := SearchElement(AccFirefox, ROLE_SYSTEM_LISTITEM := 0x22, Folder, "")
AccElem.accDoDefaultAction(0)
sleep 100
Send {Enter}
msgbox done
return
#IfWinActive
SearchElement(ParentElement, params*)
{
found := 1
for k, v in params {
(k = 1 && ParentElement.accRole(0) != v && found := "")
(k = 2 && ParentElement.accName(0) != v && found := "")
(k = 3 && ParentElement.accValue(0) != v && found := "")
}
if found
Return ParentElement
for k, v in Acc_Children(ParentElement)
if obj := SearchElement(v, params*)
Return obj
}
Acc_Init()
{
Static h
If Not h
h:=DllCall("LoadLibrary","Str","oleacc","Ptr")
}
Acc_ObjectFromWindow(hWnd, idObject = 0)
{
Acc_Init()
If DllCall("oleacc\AccessibleObjectFromWindow", "Ptr", hWnd, "UInt", idObject&=0xFFFFFFFF, "Ptr", -VarSetCapacity(IID,16)+NumPut(idObject==0xFFFFFFF0?0x46000000000000C0:0x719B3800AA000C81,NumPut(idObject==0xFFFFFFF0?0x0000000000020400:0x11CF3C3D618736E0,IID,"Int64"),"Int64"), "Ptr*", pacc)=0
Return ComObjEnwrap(9,pacc,1)
}
Acc_Query(Acc) { ; thanks Lexikos - www.autohotkey.com/forum/viewtopic.php?t=81731&p=509530#509530
try return ComObj(9, ComObjQuery(Acc,"{618736e0-3c3d-11cf-810c-00aa00389b71}"), 1)
}
Acc_Error(p="") {
static setting:=0
return p=""?setting:setting:=p
}
Acc_Children(Acc) {
if ComObjType(Acc,"Name") != "IAccessible"
ErrorLevel := "Invalid IAccessible Object"
else {
Acc_Init(), cChildren:=Acc.accChildCount, Children:=[]
if DllCall("oleacc\AccessibleChildren", "Ptr",ComObjValue(Acc), "Int",0, "Int",cChildren, "Ptr",VarSetCapacity(varChildren,cChildren*(8+2*A_PtrSize),0)*0+&varChildren, "Int*",cChildren)=0 {
Loop %cChildren%
i:=(A_Index-1)*(A_PtrSize*2+8)+8, child:=NumGet(varChildren,i), Children.Insert(NumGet(varChildren,i-8)=9?Acc_Query(child):child), NumGet(varChildren,i-8)=9?ObjRelease(child):
return Children.MaxIndex()?Children:
} else
ErrorLevel := "AccessibleChildren DllCall Failed"
}
if Acc_Error()
throw Exception(ErrorLevel,-1)
}