life ideas

October 23, 2006

basic tutaorial on AutoHotKey

Filed under: Uncategorized — manoftoday @ 8:12 pm

0) hotkeys

 

!: Sends an ALT keystroke. For example, Send This is text!a would send the keys “This is text” and then press ALT+a. Note: !A produces a different effect in some programs than !a. This is because !A presses ALT+SHIFT+A and !a presses ALT+a. If in doubt, use lowercase.

+: Sends a SHIFT keystroke. For example, Send +abC would send the text “AbC”, and Send !+a would press ALT+SHIFT+a.

^: Sends a CONTROL keystroke. For example, Send ^!a would press CTRL+ALT+a, and Send ^{Home} would send CONTROL+HOME. Note: ^A produces a different effect in some programs than ^a. This is because ^A presses CONTROL+SHIFT+A and ^a presses CONTROL+a. If in doubt, use lowercase.

#: Sends a WIN keystroke, therefore Send #e would hold down the Windows key and then press the letter “e”.

1) use IfWinActive and if  else

;use the F1 & F2 keys to switch tabs

F1::
IfWinActive, ahk_class TFormEditPadLite
{
  PostMessage, 0x111, 83,,, ahk_class TFormEditPadLite ; prev tab
  return
}
else
Send, {F1}
return

 

$F2::
IfWinActive, ahk_class TFormEditPadLite
{
  PostMessage, 0x111, 82,,, ahk_class TFormEditPadLite ; next tab
  return
}
else
Send, {F2}
return

2) loop

 

Loop %RunCount%
{
	Run C:\Check Server Status.exe
	Sleep 60000  ; Wait 60 seconds.
}

In the above, the loop is performed the specified number of times unless RunCount contains 0, in which case the loop is skipped entirely.

A loop may also terminate itself when one or more conditions change. The following example clicks the left mouse button repeatedly while the user is holding down the F1 key:

$F1::  ; Make the F1 key into a hotkey (the $ symbol facilitates the "P" mode of GetKeyState below).
Loop  ; Since no number is specified with it, this is an infinite loop unless "break" or "return" is encountered inside.
{
	if not GetKeyState("F1", "P")  ; If this statement is true, the user has physically released the F1 key.
		break  ; Break out of the loop.
	; Otherwise (since the above didn't "break"), keep clicking the mouse.
	Click  ; Click the left mouse button at the cursor's current position.
}
return

3) variable

 

MyVar1 = 123
MyVar2 = my string

To compare the contents of a variable to a number or string, follow these examples:

if MyVar2 = my string
{
	MsgBox MyVar2 contains the string "my string".
}
if MyVar1 >= 100
{
	MsgBox MyVar1 contains %MyVar1%, which is a number greater than or equal to 100.
}
 
if ErrorLevel <> FAIL
{
}
if (ItemCount > ItemLimit)
{
	MsgBox The value in ItemCount, which is %ItemCount%, is greater than %ItemLimit%.
}

Notice that the first line of the example above contains parentheses. The parentheses signify that the if-statement contains an expression.

NetPrice := Price * (1 - Discount/100)

4) logic

if (ColorName <> “” AND not FindColor(ColorName))
  MsgBox %ColorName% could not be found.

5) share functions

 

Using #Include to Share Functions Among Multiple Scripts

The #Include directive may be used (even at the top of a script) to load functions from an external file.

Explanation: When the script’s flow of execution encounters a function definition, it jumps over it (using an instantaneous method) and resumes execution at the line after its closing brace. Consequently, execution can never fall into a function from above, nor does the presence of one or more functions at the very top of a script affect the auto-execute section.

6) use pid 

*) from process name to pid

Process, Exist, asshole.exe
AssholePID=%Errorlevel%
if AssholePID

{
   msgbox, Gotcha Asshole! (%AssholePID%)

   ; To use a pid…

   ; IfWinActive, ahk_pid %AssholePID%

   ; or WinGet, AssholeHWND, id, ahk_pid %AssholePID%   ; use pid to get window id . a.k.a hwnd 

 

   ;  note, window id is a different cencept

   ;WinGet, notepad1, ID, Untitled – Notepad  ;the notepad1 is windows id, we can then use it to minimize or close

   ; WinMinimize, ahk_id %notepad1%  
}

else
   msgbox, F**k!@#!@#!@

 

*) from window id  to pid

WinGet, pid_explorer, PID, ahk_id %hw_notification_area%

 

     *) enumerate processes

 

Gui, Add, ListView, x5 y5 w400 h200, PID|file name
Gui, Show, x50 y50, EnumProcesses experiment
total := EnumProcesses( pid_list )
loop, parse, pid_list, |
   LV_Add( “”, A_LoopField, GetModuleFileNameEx( A_LoopField ) )
LV_ModifyCol( 1, “Integer Sort AutoHdr” )
LV_ModifyCol( 2, “AutoHdr” )
return

GuiClose:
ExitApp

EnumProcesses( byref r_pid_list )
{
   if A_OSVersion in WIN_95,WIN_98,WIN_ME
   {
      MsgBox, This Windows version (%A_OSVersion%) is not supported.
      return, false
   }
   pid_list_size := 4*1000
   VarSetCapacity( pid_list, pid_list_size )
   status := DllCall( “psapi.dll\EnumProcesses”, “uint”, &pid_list, “uint”, pid_list_size, “uint*”, pid_list_actual )
   if ( ErrorLevel or !status )
      return, false
   total := pid_list_actual//4
   r_pid_list=
   address := &pid_list
   loop, %total%
   {
      r_pid_list := r_pid_list “|” ( *( address )+( *( address+1 ) << 8 )+( *( address+2 ) << 16 )+( *( address+3 ) << 24 ) )
      address += 4
   }
   StringTrimLeft, r_pid_list, r_pid_list, 1
   return, total
}

GetModuleFileNameEx( p_pid )
{
   if A_OSVersion in WIN_95,WIN_98,WIN_ME
   {
      MsgBox, This Windows version (%A_OSVersion%) is not supported.
      return
   }
   h_process := DllCall( “OpenProcess”, “uint”, 0x10|0x400, “int”, false, “uint”, p_pid )
   if ( ErrorLevel or h_process = 0 )
      return
   name_size = 255
   VarSetCapacity( name, name_size )
   result := DllCall( “psapi.dll\GetModuleFileNameExA”, “uint”, h_process, “uint”, 0, “str”, name, “uint”, name_size )
   DllCall( “CloseHandle”, h_process )
   return, name
}

or through pslist

; Get list of running processes with PSList http://www.sysinternals.com/Utilities/PsList.html

 

RunWait %comspec% /c pslist -t >list.txt, , Hide
Loop, Read, list.txt
{
  if A_LoopReadLine not contains Russinovich,Sysinternals,Process,Name,Idle
  Loop, parse, A_LoopReadLine, %A_Space%
   {
     if A_LoopField !=
        count++
         if count = 2 ; pid column
         {
           name := getmodulefilenameex(A_LoopField) ; MsgBox, %A_LoopField%
            ; use splitpath to obtain drive letter of each app:     
            SplitPath, name, , , , , Drive
            if Drive = %mydrive%
               WinClose, ahk_pid %pid%
            count=
            break
         }   
   }
}
return

combined effect

 

; code by Serenity, shimanov
; pieced together and modified by corrupt
if A_OSVersion in WIN_95,WIN_98,WIN_ME
{
  MsgBox, 16, Error, This Windows version (%A_OSVersion%) is not supported.
  ExitApp
}
Gui, Add, Button, x22 y80 w75 h23 gCloseApps, OK
Gui, Add, Button, x103 y80 w75 h23 gGuiClose, Cancel
Gui, Add, Text, x14 y10 w180 h15 , Please choose your device from the list:
Gui, Add, DropDownList, x16 y40 w170 h120 Choose1 vList1, 
SplashTextOn, 200, 60,, Please wait.`n Generating a list of drives on your system…
driveget, list, list  ; all drives
stringlen, len, list
loop, %len%
{
  stringleft, drive, list, 1
  If drive <> A
    driveget, label, label, %drive%:
  GuiControl,,List1, %drive%:     %label%
  stringtrimleft, list, list, 1
}
GuiControl,Choose, List1, 1
Gui, Show, h116 w200, Close Programs
SplashTextOff
Return
CloseApps:
GuiControlGet, List1
Gui, Hide
DetectHiddenWindows, On
stringleft, mydrive, List1, 2
total := EnumProcesses( pid_list )
; get PID for this script to avoid self destruction
Process, Exist
this_pid = %ErrorLevel%
loop, parse, pid_list, |
{
  lname := GetModuleFileNameEx( A_LoopField )
  If lname<>
  {                 
    ; use splitpath to obtain drive letter of each app:     
    SplitPath, lname, , , , , Drive
    ; close the program if drive matches:
    if ( Drive = mydrive AND A_LoopField <> this_pid )
    {
      WinKill, ahk_pid %A_LoopField%
      Process, Exist, %A_LoopField%
      If (ErrorLevel)
      {
        Process, Close, %A_LoopField%
        If ErrorLevel = 0
        {
          RetError := KillProcess( A_LoopField )
          If RetError = 0
            MsgBox, %lname% is not responding. `nPlease manually close this application
        }
      }
    }
  }
}
MsgBox, 64, Done, Finished processing drive %mydrive%
GuiClose:
ExitApp
EnumProcesses( byref r_pid_list )
{
   pid_list_size := 4*1000
   VarSetCapacity( pid_list, pid_list_size )
   status := DllCall( “psapi.dll\EnumProcesses”, “uint”, &pid_list, “uint”, pid_list_size, “uint*”, pid_list_actual )
   if ( ErrorLevel or !status )
      return, false
   total := pid_list_actual//4
   r_pid_list=
   address := &pid_list
   loop, %total%
   {
      r_pid_list := r_pid_list “|” ( *( address )+( *( address+1 ) << 8 )+( *( address+2 ) << 16 )+( *( address+3 ) << 24 ) )
      address += 4
   }
   StringTrimLeft, r_pid_list, r_pid_list, 1
   return, total
}
GetModuleFileNameEx( p_pid )
{
   h_process := DllCall( “OpenProcess”, “uint”, 0x10|0x400, “int”, false, “uint”, p_pid )
   if ( ErrorLevel or h_process = 0 )
      return
   name_size = 255
   VarSetCapacity( name, name_size )
   result := DllCall( “psapi.dll\GetModuleFileNameExA”, “uint”, h_process, “uint”, 0, “str”, name, “uint”, name_size )
   DllCall( “CloseHandle”, h_process )
   return, name
}
KillProcess( p_pid )
{
   h_process := DllCall( “OpenProcess”, “uint”, 0xF0000|0x100000|0xFFF, “int”, false, “uint”, p_pid )
   if ( ErrorLevel or h_process = 0 )
      return
   result := DllCall( “TerminateProcess”, “uint”, h_process, “uint”, 0)
   DllCall( “CloseHandle”, h_process )
   return, result
}

  • use output from a command

Testing shows that due to file caching, a temporary file can be very fast for relatively small outputs. In fact, if the file is deleted immediately after use, it often does not actually get written to disk. For example:

RunWait %comspec% /c dir > C:\My Temp File.txt
FileRead, VarToContainContents, C:\My Temp File.txt
FileDelete, C:\My Temp File.txt

     *) get pid from Run

Run, notepad,,, PID

*) getpid from active window or title

WinGet, active_pid, PID, A
WinGet, active_pid, PID, Untitled-Notepad 
;get pid of  AutoHotKey script

DetectHiddenWindows on
WinGet, scriptPID, PID, %A_ScriptFullPath% – AutoHotkey v
MsgBox, PID=%scriptPID%

*)Get windows id from mouse position

 

CoordMode, Mouse, Relative
SysGet, TitleBarHeight, 4 ; 4 is SM_CYCAPTION

MButton::
MouseGetPos,, ClickY, WindowIDClicked
If, ClickY <= %TitleBarHeight%
  {
  WinGet, WindowPIDClicked, PID, ahk_id %WindowIDClicked%
  WinClose, ahk_pid %WindowPIDClicked%
  }
Return
Return

 

 

7) loop through windows

 

WinGet, id, list
Loop, %id%
{
   loop_id:=id%a_index%
   WinGetClass, loop_class, ahk_id %loop_id%
   ;IfNotInString, loop_class, Afx:400000:8:10011:0:   ; for you (uncomment)
   IfNotInString, loop_class, Note                  ; I tested on notepad
      continue
   Else
   {
      assid:=loop_id
      assclass:=loop_class
      WinGet, asspid, pid, ahk_id %assid%
      WinGetTitle, asstitle, ahk_id %assid%
      msgbox, 64, ,
      (LTrim
      Gotcha Asshole!
      PID: %asspid%
      ID: %assid%
      Title: %asstitle%
      Class: %assclass%
      )
      exit
   }
}
msgbox, 16, , Couldn’t find asshole!

8) refresh desktop icons

 

WinGet, hw_program_manager, ID, Program Manager ahk_class Progman
;MsgBox, % hw_program_manager
hw_SHELLDLL_DefView := FindWindowEx( hw_program_manager, 0, “SHELLDLL_DefView”, 0 )
;MsgBox, % hw_SHELLDLL_DefView
hw_FolderView := FindWindowEx( hw_SHELLDLL_DefView, 0, “SysListView32”, “FolderView” )
;MsgBox, % hw_FolderView
MsgBox, Now you see them …
WinHide, ahk_id %hw_FolderView%
MsgBox, .. now you dont!
WinShow, ahk_id %hw_FolderView%
return
FindWindowEx( p_hw_parent, p_hw_child, p_class, p_title )
{
   if ( p_title = 0 )
      type_title = uint
   else
      type_title = str
   return, DllCall( “FindWindowEx”
                  , “uint”, p_hw_parent
                  , “uint”, p_hw_child
                  , “str”, p_class
                  , type_title, p_title )
}

 

9) customized menu

 

#SingleInstance ignore
#Persistent
SetKeyDelay, -1
MsgBox, 4096, AbrExpansion, AbrExpansion is now loaded. You can exit this program by pressing Shift+E or by right clicking`non it’s system tray icon. Press “Ok” to exit this dialogue, and enable Abbreviation Expansion.
Menu, tray, NoStandard
menu, tray, add
menu, tray, add, Exit
menu, tray, add
Return
Exit:
Send, {Shift Down}e{Shift Up}
Return
+e::
Msgbox, 4096, AbrExpansion, Thank you for using AbrExpansion.`nThe program will now exit., 6
ExitApp
Return

Advertisements

5 Comments »

  1. I love the abundance amount of comments in your code.

    Comment by YourTutaorialsucks — April 21, 2010 @ 7:35 am

  2. Thanks for finally talking about >basic tutaorial on AutoHotKey | life ideas
    <Liked it!

    Comment by jackpot 6000 — May 29, 2013 @ 10:50 pm

  3. I tend not to leave a comment, however I looked
    at some of the remarks here basic tutaorial on AutoHotKey |
    life ideas. I do have 2 questions for you if it’s okay. Could it be simply me or does it give the impression like some of these comments appear as if they are coming from brain dead individuals? 😛 And, if you are posting on additional online social sites, I would like to keep up with you. Could you make a list of the complete urls of all your social networking pages like your Facebook page, twitter feed, or linkedin profile?

    Comment by ejaculation guru free Download — June 1, 2013 @ 11:21 pm

  4. At this time I am ready to do my breakfast, once having my breakfast coming again to read other news.

    Comment by Osvaldo — June 2, 2013 @ 5:10 am

  5. While there are countless variables which appear to be external
    and beyond control, we can certainly position ourselves better in relation to those variables, if we know HOW.
    It is the time for females and feminine energy to have their
    due, a time where emotion and intuition will wax
    like the fullness of the moon on a clear
    and starry night. You can get a numerology readings for your personal year from a numerologist.

    Comment by Numerology Diet PDF — September 13, 2013 @ 6:55 pm


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: