AutoHotKey script for simple function - scripting

How can I write a .ahk script to automate the process of
"press and hold 'key1' 2 second",
"press and hold 'key2' 2 seconds",
"press and hold 'key3' 2 seconds",
"right click, wait 2 seconds", and repeat.
I've never scripted for automated actions on the keyboard before so this is all new territory for me. I assume anyone with some experience could implement the above in a minute or two.
EDIT: I would also like to be able to call this script to start with some sort of key combination, like "wait for alt+a , then execute".

Hope this get's you going..
!a:: ; Alt+a to start script
Loop
{ ; Start of loop
GetKeyState, keystate, Pause, P ; Get the state of the Pause key
if keystate = D ; The Pause key was held down, break out of the loop.
break ; Stop loop when the Pause key was held down
Send, {Space Down} ; This will NOT autorepeat
Sleep 2000 ; Wait 200 ms
Send, {Space Up} ; Release the key
GetKeyState, keystate, Pause, P ; Get the state of the Pause key
if keystate = D ; The Pause key was held down, break out of the loop.
break ; Stop loop when the Pause key was held down
Send, {b Down} ; This will NOT autorepeat
Sleep 2000 ; Wait 200 ms
Send, {b Up} ; Release the key
GetKeyState, keystate, Pause, P ; Get the state of the Pause key
if keystate = D ; The Pause key was held down, break out of the loop.
break ; Stop loop when the Pause key was held down
MouseClick, left, 150,150 ; Click the mouse at 150X,150Y pixels, check exact mouse coordinates with AHK Window Spy
} ; End of loop
return ; End of script
P.s. Instead of adding the Break trap after each key, you could also add a hotkey to run exitapp.

Related

autohotkey variables not updating on keypresses

I have a number of hotkeys which go through various processes and sleep for certain periods of time to allow animations to be shown. I want to setup a variable to allow only 1 to activate at a time...so if I hit the first and then the second....the second doesn't do anything until the first completes. Similarly I don't want to double activate any of them by mashing the same key right after I first press it.
F4:ExitApp
#IfWinActive ahk_class notepad
a::
if (work:=true){
work:=false
soundbeep
;do something
sleep 1000
work:=true
}
return
b::
if (work:=true){
work:=false
soundbeep
;do something else
sleep 2000
work:=true
}
return
i.e. if I hit 'a'....'b' cannot activate until the sleep of 'a' ends. Nor should 'a' be able to activate a second time...at least not until its sleep ends and work=true again.
This leaves 2 problems. I need to first somehow specify the initial value of 'work=true'. I do not know how to do this in the traditional sense. Simply putting it at the top of the code doesn't work. Second problem, putting this in another key...like enter:: work:=true return....and pressing that key initially...this doesn't work as it allows b to beep while a is still in its sleep phase. So maybe the code above is flawed to begin with as well. Individual keys seem to respect themselves and not re-initialize until after the first instance has completed...so the beeps work if I just mash 1 key. Also I don't want to have to press enter to get the code to work after loading the script.
Is there an easy cheat here? Like in lua undeclared variables are automatically false... so I could just swap to if (work=false){...., I can't find any such behaviour with autohotkey though.
As requested, here is a different solution that uses variable logic to allow or prevent hotkey commands from executing:
#IfWinActive ahk_class Notepad
work:=true
a::
if(work){
work:=false
soundbeep
;do something
sleep 1000
work:=true
}
return
b::
if(work){
work:=false
soundbeep
;do something else
sleep 2000
work:=true
}
return
Update: Breakdown of how it works
First, the script begins in the auto-execute section. As summarized elegently by maul-esel
When an AutoHotkey script launches, it just starts execution from the
first line of your script. It continues from there line by line until
it hits an end point. This is called the auto-execute section.
As such, by including work:=true in this section of the script, not only are we initializing the value of the variable before any hotkeys are triggered, we set the scope of work to be a global variable, accessible across different hotkeys.
The rest of the script is a bit more straightforward, where each hotkey is essentially (in pseudocode):
When the hotkey is triggered
if work is true
set work to false
Beep and etc.
Wait for some amount of time
Then set work back to true so that another command can be run
End the hotkey
One simple way to do it would be to declare #MaxThreads 1 at the top of your script.
As a side note, there appear to be a few other syntax errors in the script. For example, when comparing values (like in an if statement), you still use the regular, single = and not the assignment :=. Also, the ahk_class is case sensitive, and as such #IfWinActive ahk_class notepad should be replaced with #IfWinActive ahk_class Notepad.
Updated Code (Work Variable logic was removed as it is no longer needed):
#MaxThreads 1
#IfWinActive ahk_class Notepad
a::
soundbeep
;do something
sleep 1000
return
b::
soundbeep
;do something else
sleep 2000
return

AutoHotKey: wait for process, breaking on user input

A script is waiting for a process to start; it shall do so indefinitely, but only as long as there is no human input. In another words: the script shall wait for either process start or human input, whichever comes first (also, the process may already be running when the script starts, in which case the script shall close immediately). I have thought of something like this, but there’s likely a better way, since this loop doesn’t break with input:
while (A_TimeIdlePhysical > 100) {
Process, Wait, SomeProcess.exe
}
Any ideas?
Tested with notepad:
#Persistent
SetTimer, DetectProcess, 50
return
DetectProcess:
If (ProcessExist("notepad.exe")) ; if the process is already running
ExitApp
; otherwise:
If (A_TimeIdlePhysical > 100) ; as long as there is no human input
{
If (ProcessExist("notepad.exe")) ; wait for either process start
ExitApp
}
else ; or human input
ExitApp
return
ProcessExist(ProcessName){
Process, Exist, %ProcessName%
return Errorlevel
}

how to read "enter" key in fortran

The following fortran 90 program can read in a text file and then print it out on the screen. It has an added feature that when the output covers the whole screen it will pause and wait for the user to press enter key to continue. Currently I use the "PAUSE" to implement this feature. But I would like to know the direct way of reading in the enter key. Please do offer your wisdom. I appreciate it!
program ex0905
implicit none
character(len=79) :: filename
character(len=79) :: buffer
integer, parameter :: fileid = 10
integer :: status = 0,count=0
logical alive
character(len=1) :: c
write(*,*) "Filename:"
read (*,"(A79)") filename
inquire( file=filename, exist=alive)
if ( alive ) then
open(unit=fileid, file=filename, &
access="sequential", status="old")
do while(.true.)
read(unit=fileid, fmt="(A79)", iostat=status ) buffer
if ( status/=0 ) exit
!write(*,"(A79)") buffer
count = count+1
if (count<24) then
write(*,"(A79)") buffer
else
!write(*,*) "Please type Enter to continue: "
pause
count=0
!read(*,"(A1)") c
!if (c==char(13)) then
! write(*,"(A79)") buffer
!else
! write(*,*) "This is not the 'Enter' key!!"
! exit
!end if
end if
end do
else
write(*,*) TRIM(filename)," doesn't exist."
end if
stop
end
If you have an item in the input list for read, as you do here with the character c, execution will not proceed until you do provide an actual item to standard input.
You can instead achieve what you want by having a read(*,*) statement without input. This will wait for just the key press, discarding any input.

Change URL in script and run script again

we are using this script;
run "**C:\Program Files (x86)\Internet Explorer\iexplore.exe" http://SOMEURL.shtml**
Sleep, 10000
Send, %ROUTERUN%{tab}
Sleep, 1000
Send, %ROUTERPW%
Sleep, 1000
Send, {Tab}{Tab}{Space}
Sleep, 10000
Send, #Up
Send, {F5}
Sleep, 20000
Click, 1041, 575
Send, %CODE%
Sleep, 1000
Click, 1613, 983
Sleep, 1000
If WinExist Message from webpage
WinActivate
Sleep, 1000
Click, 392, 153
Sleep, 1000
If WinExist Message from webpage
WinActivate
Click, 219, 153
Sleep, 8000
Send, !{F4}
Sleep, 1000
FormatTime, TimeString,, LongDate
FormatTime, TimeString2,, Time
FileAppend, %VES1% %TimeString% %TimeString2% D:\Test.txt
What we would like to accomplish is, when the script is finished, to run the script again but this time with another URL on the first line.
And that times 38.
Ofcourse I can copy/paste the script 38 times and change the line manually, but maybe there is a way of solving this with a variable or loop or something like that?
thanks
You can use an array and a loop to accomplish this. This example uses AHK_L
arr := []
arr[1] := "www.google.com"
arr[2] := "yahoo.com"
arr[3] := "www.amazon.com"
Loop % arr.MaxIndex()
{
site := arr[A_Index]
Run, "C:\Program Files (x86)\Internet Explorer\iexplore.exe" %site%
;;; Other code here ;;;
}
On top of the answer from Elliot, when you use Google Chrome, you can "detect" if the page is ready downloading by monitoring the mouse status (pointer or hourglass) through the following code:
while (A_Cursor = "AppStarting") ; While hourglass do sleep else continue
Sleep, 500 ; Wait 500 ms then run while again...
Your next lines of code....
This way you don't have to put long sleep timers in your code, just to be sure that the page is downloaded...
Also, if you want to store the login & password per site, you could use "multi-dimensional" arrays
Arr[1,1] := "www.google.com"
Arr[1,2] := "abc#google.com"
Arr[1,3] := "s3cr3tp#ssw0rd"
Arr[2,1] := "yahoo.com"
Arr[2,2] := "abc#yahoo.com"
Arr[2,3] := "s3cr3tp#ssw0rd"
etc.

Best AutoHotKey macros? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I use AutoHotKey for Windows macros. Most commonly I use it to define hotkeys that start/focus particular apps, and one to send an instant email message into my ToDo list. I also have an emergency one that kills all of my big memory-hogging apps (Outlook, Firefox, etc).
So, does anyone have any good AHK macros to share?
Very simple and useful snippet:
SetTitleMatchMode RegEx ;
; Stuff to do when Windows Explorer is open
;
#IfWinActive ahk_class ExploreWClass|CabinetWClass
; create new folder
;
^!n::Send !fwf
; create new text file
;
^!t::Send !fwt
; open 'cmd' in the current directory
;
^!c::
OpenCmdInCurrent()
return
#IfWinActive
; Opens the command shell 'cmd' in the directory browsed in Explorer.
; Note: expecting to be run when the active window is Explorer.
;
OpenCmdInCurrent()
{
WinGetText, full_path, A ; This is required to get the full path of the file from the address bar
; Split on newline (`n)
StringSplit, word_array, full_path, `n
full_path = %word_array1% ; Take the first element from the array
; Just in case - remove all carriage returns (`r)
StringReplace, full_path, full_path, `r, , all
full_path := RegExReplace(full_path, "^Address: ", "") ;
IfInString full_path, \
{
Run, cmd /K cd /D "%full_path%"
}
else
{
Run, cmd /K cd /D "C:\ "
}
}
Here is so simple but useful script:
^SPACE:: Winset, Alwaysontop, , A
Use CTRL + Space to set any window always on top.
Add surrounding quotes on selected text/word
Useful when writing emails or during coding...
Doubleclick word, hit Win+X, have quotes around
; Win + X
#x:: ; Attention: Strips formatting from the clipboard too!
Send ^c
clipboard = "%clipboard%"
; Remove space introduced by WORD
StringReplace, clipboard, clipboard,%A_SPACE%",", All
Send ^v
return
; I have this in my start menu so that I won't ruin my ears when I put on my headphones after rebooting my computer
sleep, 5000
SoundSet, 1.5 ; really low volume
I create new Outlook objects with AutoHotKey
; Win+Shift+M = new email
#+m:: Run "mailto:"
; Outlook
#^M:: Run "%ProgramFiles%\Microsoft Office\Office12\OUTLOOK.EXE" /recycle
; Win+Shift+A = create new calendar appointment
#+A:: Run "%ProgramFiles%\Microsoft Office\Office12\OUTLOOK.EXE"/c ipm.appointment
; Win+Shift+T = create new Task
; Win+Shift+K = New task
#+T:: Run "%ProgramFiles%\Microsoft Office\Office12\OUTLOOK.EXE"/c ipm.task
#+K:: Run "%ProgramFiles%\Microsoft Office\Office12\OUTLOOK.EXE"/c ipm.task
Here's a dead-simple snippet to quickly close the current window using a mouse button.
It's one of the actions you perform most often in Windows, and you'll be surprised at how much time you save by no longer having to shoot for that little X. With a 5-button mouse, I find this a very useful reassignment of the "Forward" button.
#IfWinActive ;Close active window when mouse button 5 is pressed
XButton2::
SendInput {Alt Down}{F4}{Alt Up}
Return
#IfWinActive
To take into account programs that use tabbed documents (like web browsers), here's a more comprehensive version:
;-----------------------------------------------------------------------------
; Bind Mouse Button 5 to Close Tab / Close Window command
;-----------------------------------------------------------------------------
; Create a group to hold windows which will use Ctrl+F4 instead of Alt+F4
GroupAdd, CtrlCloseGroup, ahk_class IEFrame ; Internet Explorer
GroupAdd, CtrlCloseGroup, ahk_class Chrome_WidgetWin_0 ; Google Chrome
; (Add more programs that use tabbed documents here)
Return
; For windows in above group, bind mouse button to Ctrl+F4
#IfWinActive, ahk_group CtrlCloseGroup
XButton2::
SendInput {Ctrl Down}{F4}{Ctrl Up}
Return
#IfWinActive
; For everything else, bind mouse button to Alt+F4
#IfWinActive
XButton2::
SendInput {Alt Down}{F4}{Alt Up}
Return
#IfWinActive
; In FireFox, bind to Ctrl+W instead, so that the close command also works
; on the Downloads window.
#IfWinActive, ahk_class MozillaUIWindowClass
XButton2::
SendInput {Ctrl Down}w{Ctrl Up}
Return
#IfWinActive
Visual Studio 2010 can't easily be added to the CtrlCloseGroup above, as it's window class / title aren't easily predictable (I think). Here's the snippet I use to handle it, including a couple additional helpful bindings:
SetTitleMatchMode, 2 ; Move this line to the top of your script
;-----------------------------------------------------------------------------
; Visual Studio 2010
;-----------------------------------------------------------------------------
#IfWinActive, Microsoft Visual Studio
; Make the middle mouse button jump to the definition of any token
MButton::
Click Left ; put the cursor where you clicked
Send {Shift Down}{F2}{Shift Up}
Return
; Make the Back button on the mouse jump you back to the previous area
; of code you were working on.
XButton1::
Send {Ctrl Down}{Shift Down}{F2}{Shift Up}{Ctrl Up}
Return
; Bind the Forward button to close the current tab
XButton2::
SendInput {Ctrl Down}{F4}{Ctrl Up}
Return
#IfWinActive
I also find it useful in Outlook to map ALT+1, ALT+2, etc. to macros I wrote which move the currently selected message(s) to specific folders (eg. "Personal Filed", "Work Filed", etc) but that's a bit more complicated.
There are tons of good ones in the AutoHotKey Forum:
http://www.autohotkey.com/forum/forum-2.html&sid=8149586e9d533532ea76e71e8c9e5b7b
How good? really depends on what you want/need.
I use this one all the time, usually for quick access to the MySQL command line.
http://lifehacker.com/software/featured-windows-download/make-a-quake+style-command-prompt-with-autohotkey-297607.php
Fix an issue when copying file to FTP server when the "Copying" dialog appears on top of the "Confirm File Replace" dialog (very annoying):
SetTimer, FocusOnWindow, 500
return
FocusOnWindow:
IfWinExist, Confirm File Replace
WinActivate
return
One to deactivate the useless Caps-lock key:
Capslock::
return
CTRL + shift + c will copy colour below cursor to the clipboard (in hexadecimal)
^+c::
MouseGetPos,x,y
PixelGetColor,rgb,x,y,RGB
StringTrimLeft,rgb,rgb,2
Clipboard=%rgb%
Return
Write your email address in the active field (Win key + m)
#m::
Send, my#email.com{LWINUP}
Sleep, 100
Send, {TAB}
return