Jump to content
Sign in to follow this  
leomoon

Hotkey Program

Recommended Posts

leomoon

Hello,

I'm trying to write a hotkey program and I know exactly how to do it but it will be hard coded and the user won't be able to edit it.

HotKeySet("{ESC}", "HotKeyPressed")
HotKeySet("^!d", "HotKeyPressed")
HotKeySet("^+x", "HotKeyPressed")

While 1
    Sleep(500)
WEnd

Func HotKeyPressed()
    Switch @HotKeyPressed
        Case "{ESC}"
            Exit
        Case "^!d"
            ShellExecute("D:\Docs")
        Case "^+x"
            ShellExecute("D:\Docs\My Portables\Burner\AnyBurn\AnyBurn.exe")
    EndSwitch
EndFunc

I want the program to read a file that has hotkeys on odd lines and paths on even lines but I don't see how the program will load into itself.

Is it even possible?

Thanks.

Share this post


Link to post
Share on other sites
gruntydatsun

yes, it is possible.   FileRead and use StringRegexp and the crlf to break the entries up.   Using the INI library might be less hassle for you though.

Share this post


Link to post
Share on other sites
leomoon

I know about the reading ini but let's say we read all the hotkeys and the paths that it has to execute. Now how do we generate a function on runtime and execute it? In he example above, that would be HotkeyPressed() function.

Share this post


Link to post
Share on other sites
gruntydatsun

sorry leomoon, i missed the point there.

looks like you can't pass arguments to a function you call from HotKeySet so i guess you'd need to be able to dynamically create the functions based on what you read off the file.

does this thread help any?

 

Share this post


Link to post
Share on other sites
leomoon

The first way is to loop and create functions but hotkeyset needs the function created already:

$ini = @ScriptDir&"\hotkeys.ini"
Global $aHotkeys = IniReadSection($ini, "Hotkeys")
Global $i

For $i = 1 To $aHotkeys[0][0]
    HotKeySet($aHotkeys[$i][0], $i)
Next

While 1
    Sleep(500)
WEnd

For $i = 1 To $aHotkeys[0][0]
    Func Eval($i)&"()"
        ShellExecute($aHotkeys[$i][1])
    EndFunc
Next

The second way is to make one function with cases which is better cuz the hotkeyset already has the function ready. I just don't know how to create the cases with the array:

$ini = @ScriptDir&"\hotkeys.ini"
Global $aHotkeys = IniReadSection($ini, "Hotkeys")
Global $i

For $i = 1 To $aHotkeys[0][0]
    HotKeySet($aHotkeys[$i][0], "HotKeyPressed")
Next

While 1
    Sleep(500)
WEnd

Func HotKeyPressed()
    Switch @HotKeyPressed
        ;Loop through array and create cases
        Case Else
            ;do nothing
    EndSwitch
EndFunc

 

Share this post


Link to post
Share on other sites
gruntydatsun

check the return value on HotKeySet, i can't get it to work unless it's fed strings, not variables

Share this post


Link to post
Share on other sites
gruntydatsun

Its a dead quiet day here so I've been mucking around with it

$aHotkeys = IniReadSection(@ScriptDir & "\test.ini", "Hotkeys")

For $i = 1 To $aHotkeys[0][0]
    HotKeySet($aHotkeys[$i][0],"HotKeyPressed")
Next

While 1
    Sleep(500)
WEnd

Func HotKeyPressed()
    for $x = 1 to UBound($aHotkeys)-1
        if @HotKeyPressed = $aHotkeys[$x][0] Then Execute($aHotkeys[$x][1])
    Next
EndFunc

and make a file called test.ini in the root of the program folder with contents:
 

[Hotkeys]
+!d=ShellExecute("D:\backup")
+!x=ShellExecute("D:\repo")

this works for me

  • Like 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • xtcislove
      By xtcislove
      I have a script which is not very good written and could be mouch smaller etc. but thats not the point.

      The Problem is that sometimes my script stuck and the reason is i am using a tray menu and hotkeys to call other functions...

      Is there a way, to only allow a new hotkey function to get started when the other stopped? 

      Or a way to always return to the tray menu? 
       
      #RequireAdmin #include <StringConstants.au3> #include <TrayConstants.au3> #include <Process.au3> #include <File.au3> #include <FileConstants.au3> #include "ScalingMessageBox.au3" #include "_GetCurrentSoundDevice.au3" #include <Array.au3> #include <WinAPI.au3> #include <_MuteActiveWindow.au3> Opt("TrayMenuMode", 3) Opt("TrayIconDebug", 1) Global $IsMinimized = 0 Global $ActualWindow HotKeySet("+!s", "SwitchSoundDevice") ; Shift-Alt-t. - Hotkey to switch between devices. HotKeySet("+!k", "AppMinMax") ; Shift-Alt-k. - Hotkey to minimize/maximize current app. HotKeySet("+!t", "Taskkiller") ; Shift-Alt-t. - Hotkey to kill current app. HotKeySet("+!f", "SteamFriends") ; Shift-Alt-f. - Hotkey to open Steam Friends. HotKeySet("+!n", "Notepad") ; Shift-Alt-N. - Hotkey for Notepad Function. HotKeySet("+!m", "_MuteActiveWindow") ; Shift-Alt-M. - Hotkey to mute active window sound. HotKeySet("+!c", "SciTEClipboard") ; Shift-Alt-M. - Hotkey to mute active window sound. If Not ProcessExists("aida64.exe") Or Not ProcessExists("RemotePanel.exe") Or Not ProcessExists("PerfTune.exe") Then local AutoStart() local $dcPID[3] $dcPID[0] = 2 $dcPID[1] = ShellExecute("D:\Batch Space\WindowsAutomation\DownloadControl.au3") $dcPID[2] = ShellExecute("D:\Batch Space\WindowsAutomation\FrapsMessage.au3") SwitchSoundDevice("Speaker") ;-> Selecting Speaker on Startup. Local $iSteam = TrayCreateItem("Steam") TrayCreateItem("") ; Create a separator line. Local $iMobileAuthenticator = TrayCreateItem("Mobile Authenticator") TrayCreateItem("") ; Create a separator line. Local $iGames = TrayCreateMenu("Games") ; Create a tray menu sub menu with two sub items. Local $iPUBG = TrayCreateItem("PLAYERUNKNOWN'S BATTLEGROUNDS", $iGames) Local $iDARWIN = TrayCreateItem("Darwin Project", $iGames) Local $iFORTNITE = TrayCreateItem("Fortnite Battle Royale", $iGames) TrayCreateItem("") ; Create a separator line. Local $iStopWatch = TrayCreateItem("StopWatch") TrayCreateItem("") ; Create a separator line. Local $iTimer = TrayCreateItem("Timer") TrayCreateItem("") ; Create a separator line. Local $iTaskManager = TrayCreateItem("TaskManager") TrayCreateItem("") ; Create a separator line. Local $iRestartSensor = TrayCreateItem("RestartSensor") TrayCreateItem("") ; Create a separator line. Local $iShutdown = TrayCreateItem("Shutdown") TrayCreateItem("") ; Create a separator line. Local $idExit = TrayCreateItem("Exit") TraySetState($TRAY_ICONSTATE_SHOW) ; Show the tray menu. While 1 Switch TrayGetMsg() Case $iSteam ShellExecute("D:\Spiele\Steam\Steam.exe") Case $iMobileAuthenticator ShellExecute("D:\Batch Space\WindowsAutomation\MobileAuthenticator.au3") Case $iPUBG ShellExecute("steam://rungameid/578080") Case $iDARWIN ShellExecute("steam://rungameid/544920") Case $iFORTNITE Run("D:\Spiele\Epic Games\Fortnite\FortniteGame\Binaries\Win64\FortniteClient-Win64-Shipping.exe") Case $iStopWatch ShellExecute("D:\Batch Space\WindowsAutomation\StopWatch.au3") Case $iTimer ShellExecute("D:\Batch Space\Timer\Timer.bat") Case $iTaskManager ShellExecute("D:\Batch Space\TaskManager\Taskmanager.bat") Case $iRestartSensor If ProcessExists("RemotePanel.exe") Then ProcessClose("RemotePanel.exe") If ProcessExists("aida64.exe") Then ProcessClose("aida64.exe") ScreenState() ShellExecute("C:\Program Files (x86)\FinalWire\AIDA64 Extreme\aida64.exe","",@SW_SHOWNORMAL) Run("C:\Program Files (x86)\Odospace\Remote Panel\RemotePanel.exe") Case $iShutdown ShellExecute("D:\Batch Space\WindowsAutomation\Shutdown.au3") Case $idExit for $i = 1 To $dcPID[0] If ProcessExists($dcPID[$i]) Then ProcessClose($dcPID[$i]) Next Exit EndSwitch WEnd Func SciTEClipboard() _sMsgBox("SciTE Clipboard", "MsgBox;_sMsgBox", "Choose a option: ", "db=1;to=7;tr=10") if @extended = 1 Then ClipPut('MsgBox(0, "Test", "Test")') if @extended = 2 Then ClipPut('_sMsgBox("Test", "Ok", "Test", "")'&@CRLF) Return EndFunc Func Notepad() _sMsgBox("Launch SciTE or Notepad++?", "SciTE;Notepad++", "Launch SciTE or Notepad++?", "db=1;to=10;tr=10") if @extended = 1 Then Run("C:\Program Files (x86)\AutoIt3\SciTE\SciTE.exe") if @extended = 2 Then Run("C:\Program Files (x86)\Notepad++\notepad++.exe") EndFunc Func SwitchSoundDevice($SoundDevice = "") local $NirCMD = "D:\Batch Space\tools\nircmd.exe" ; nircmd.exe path local $IconPath = "D:\Batch Space\ICON\" ; Icons path local $CurrentDevice = StringLeft(_GetCurrentSoundDevice(), 7) If Not IsDeclared("SoundDevice") Then if $CurrentDevice = "Headset" Then Local $SoundDevice = "Speaker" if $CurrentDevice = "Speaker" Then Local $SoundDevice = "Headset" Run($NirCMD & " setdefaultsounddevice " & $SoundDevice) EndIf TrayTip($SoundDevice & " active.", " ", 1, $TIP_ICONASTERISK) TraySetToolTip($SoundDevice & " active.") TraySetIcon($IconPath & $SoundDevice & ".ico") Local $sActualWindow = WinGetTitle("[ACTIVE]") If $SoundDevice = "Headset" Then If Not ProcessExists("ts3client_win64.exe") Then _sMsgBox("Headset Active, Teamspeak not.", "Yes;No", "Headset active, TeamSpeak 3 is not running.", "db=1;to=10") If @extended = 1 Then ShellExecute("C:\Program Files\TeamSpeak 3 Client\ts3client_win64.exe") WinWaitActive("TeamSpeak3") EndIf EndIf EndIf If ProcessExists("ts3client_win64.exe") Then WinActivate("TeamSpeak3") If $SoundDevice = "Speaker" Then Send("!b") ; Alt + b -> Mute Mic/Speaker in Teamspeak. If $SoundDevice = "Headset" Then Send("!m") ; Alt + m -> Unmute Mic/Speaker in Teamspeak. EndIf If WinExists($sActualWindow) Then WinActivate($sActualWindow) EndFunc Func AppMinMax($IsMinimized) ;==>AppMinMax function. If $IsMinimized = 0 Then $ActualWindow = WinGetTitle("[ACTIVE]") TraySetState($TRAY_ICONSTATE_FLASH) WinSetState($ActualWindow, "", @SW_MINIMIZE) TraySetToolTip("Minimized: " & $ActualWindow) $IsMinimized = 1 else Local $Process = _ProcessGetName(WinGetProcess($ActualWindow)) For $i = 1 to _FileCountLines("D:\Batch Space\WindowsAutomation\Games.txt") $Line = FileReadLine("D:\Batch Space\WindowsAutomation\Games.txt", $i) If $line = $Process Then If WinExists($ActualWindow) Then WinActivate($ActualWindow) WinSetState($ActualWindow, "", @SW_MAXIMIZE) EndIf ExitLoop EndIf Next WinActivate($ActualWindow) TraySetToolTip("Restored: " & $ActualWindow) TraySetState($TRAY_ICONSTATE_STOPFLASH) $IsMinimized = 0 EndIf EndFunc ;==>AppMinMax stop. Func Taskkiller() ;==>Taskkiller function. local $Window = WinGetTitle("[ACTIVE]") local $Process = _ProcessGetName(WinGetProcess($Window)) _sMsgBox("Kill " & $Process & "?", "Yes.,No.", "Do you like to kill: " &@LF&@LF& $Window & "?", "db=1;to=1,20") If @extended = 1 Then ProcessClose($Process) If WinExists($Window) Then WinActivate($Window) EndFunc ;==>Taskkiller stop. Func SteamFriends() ;==>SteamFriends function. ShellExecute("steam://open/friends/") AppMinMax(0) WinActivate("Friends") EndFunc ;==>SteamFriends stop. Func AutoStart() TraySetToolTip("Autorun active.") TraySetIcon("D:\Batch Space\ICON\Autorun.ico") TraySetState($TRAY_ICONSTATE_FLASH) RunWait('regedit /s "D:\Batch Space\WindowsAutomation\REGISTRY.reg"') ShellExecute("C:\Program Files (x86)\Intel\Intel(R) Extreme Tuning Utility\Client\PerfTune.exe","",@SW_SHOWNORMAL) WinWaitActive("Intel® Extreme Tuning Utility", "", 20) WinActivate("Intel® Extreme Tuning Utility") WinClose("Intel® Extreme Tuning Utility") If ProcessExists("RemotePanel.exe") Then ProcessClose("RemotePanel.exe") If ProcessExists("aida64.exe") Then ProcessClose("aida64.exe") ScreenState() ShellExecute("C:\Program Files (x86)\FinalWire\AIDA64 Extreme\aida64.exe","",@SW_SHOWNORMAL) Run("C:\Program Files (x86)\Odospace\Remote Panel\RemotePanel.exe") Run("G:\Programme\Tools\W10Privacy\W10Privacy.exe /s 1") BatteryLevel() TraySetState($TRAY_ICONSTATE_STOPFLASH) EndFunc Func ScreenState() FileChangeDir("C:\Program Files (x86)\Odospace\Remote Panel\adb") If ProcessExists("adb.exe") Then ProcessClose("adb.exe") Local $Odospace = StringInStr(_RunCmd('adb -s 3200d994ae6f9000 shell dumpsys activity activities | find "mFocusedActivity:"'), "com.odospace.remotepanel") If $Odospace <> 0 Then RunWait(@ComSpec & ' /c ' & "adb -s 3200d994ae6f9000 shell am force-stop com.odospace.remotepanel", @TempDir, @SW_HIDE) RunWait(@ComSpec & ' /c ' & "adb -s 3200d994ae6f9000 shell monkey -p com.odospace.remotepanel -c android.intent.category.LAUNCHER 1", @TempDir, @SW_HIDE) RunWait(@ComSpec & ' /c ' & "adb -s 3200d994ae6f9000 shell input keyevent KEYCODE_WAKEUP", @TempDir, @SW_HIDE) EndFunc Func BatteryLevel() FileChangeDir("C:\Program Files (x86)\Odospace\Remote Panel\adb") If ProcessExists("adb.exe") Then ProcessClose("adb.exe") Local $sBatteryLevel = StringTrimLeft(_RunCmd('adb -s 3200d994ae6f9000 shell dumpsys power | find "mBatteryLevel="'), 14) If $sBatteryLevel < 10 Then MsgBox(0, "Warning!", "Battery Level from Sensor Tablet is at: " & $sBatteryLevel & "%" & @CRLF & @CRLF & "Press ok to shutdown Tablet.") RunWait(@ComSpec & ' /c ' & "adb -s 3200d994ae6f9000 shell input keyevent KEYCODE_SLEEP", @TempDir, @SW_HIDE) Endif TrayTip("Tablet Battery Level is at: " & $sBatteryLevel & " %.", " ", 1, $TIP_ICONASTERISK) EndFunc Func _RunCmd($sCommand) If StringLeft($sCommand, 1) = " " Then $sCommand = " " & $sCommand Local $nPid = Run (@Comspec & " /c" & $sCommand, "", @SW_Hide, 8), $sRet = "" If @Error then Return "ERROR:" & @ERROR ProcessWait ($nPid) While 1 $sRet &= StdoutRead($nPID) If @error Or (Not ProcessExists($nPid)) Then ExitLoop WEnd Return StringStripWS($sRet, 3) EndFunc ; ==> _RunCmd  
    • nacerbaaziz
      By nacerbaaziz
      Hello
      i have searched a lot about how to run external programs with the administrator privileges without the script running with administrator privileges using autoit
      But all my attempts failed
      Finally, today I found the VBS function doing this task
      I immediately transferred it to our beloved language (autoit) and i decided to share it with you
      i hope you like it
      This is a simple example about how to use the function

      runAsAdmin("cmd.exe", "/c @echo off & cls & echo test & pause", "c:\", @sw_show)
      this is the function

      func runAsAdmin($program, $parameters = "", $workingDir = @workingDir, $show = "") local $oShell = OBJCreate("Shell.Application") if isOBJ($oShell) then local $result = $oShell.ShellExecute($program, $parameters, $workingDir, "runas", $show) else $result = false endIf return $result endFunc
       
    • kokoilie
      By kokoilie
      I'm making a program that has a combo control in a gui and back in win7 when the window was focused the scroll wheel could be used to scroll through it's contents, now i'm using win10 and i have to put the mouse on that control to scroll up and down.
      Since now the scroll wheel works depending on where the mouse is, is there a way to make it no matter where on the gui the pointer is?
      Also if the only way to do it is some complex hotkey functions will it work with pressing space to toggle a checkbox?
      If you need to see what i have so far let me know and i'll copy it here.
    • Phoenixx177
      By Phoenixx177
      I have a script that is calling 2 browser windows in my GUI and loading up the appropriate URLs.  Tested alone it works fine.  I also have another script that launches a 3rd party application in the GUI.  When I try to modify my 2nd script so that it includes the two browser windows along with the GUI, the GUI loads but not the browser windows.  Can someone get a second set of eyes on the script below and tell me where my brain jumped track please?  Many Thanks.
      #include <GUIConstants.au3> #include <Constants.au3> #include <windowsconstants.au3> #include <IE.au3> Global $oIE_google = _IECreateEmbedded() Global $oIE_autoit = _IECreateEmbedded() Opt("GUIOnEventMode", 1) ; Change to OnEvent mode $mainWindow = GUICreate("Embed Cmd", 1280, 780, 10, 10) GUISetOnEvent($GUI_EVENT_CLOSE, "CLOSEClicked") GUISetState (@SW_SHOW) GUIRegisterMsg(0xF, "WM_PAINT") ; create a borderless window that is a child to the main window $embedWindow = GUICREATE("", 700, 400, 15, 15, $WS_POPUP, -1, $mainWindow) Global $google = GUICtrlCreateObj($oIE_google, 10, 10, 1000, 300) Global $autoit = GUICtrlCreateObj($oIE_autoit, 800, 10, 500, 300) _IENavigate($oIE_google, "http://www.google.com") _IENavigate($oIE_autoit, "http://www.bing.com") DllCall("user32.dll", "hwnd", "SetParent", "hwnd", $embedWindow, "hwnd", $mainWindow) ; launch the command prompt (black on white, without the operating system message) $pid = run("C:\Program Files (x86)\Cisco\Router Manager\Router Administration.exe") ProcessWait ($pid) ; get the handle of the cmd window as i cannot be certain that there will be only one instance of the cmd running with the same window title or class $cmdHandle = _ProcessGetHWnd($pid, 2) $hWndChild = $cmdHandle[1][1] ; make the command prompt window a child to the earlier created borderless child window DllCall("user32.dll", "hwnd", "SetParent", "hwnd", $hWndChild, "hwnd", $embedWindow) ; resize the command prompt window so that its bolder and title bar are outside the borderless child window ; giving the appearance of a borderless command prompt WinMove($hWndChild, '', 10, 500, 485, 206) ;WinMove($hWndChild, '', 10, 500) WinSetState($hWndChild, '', @SW_SHOW) WinSetState($embedWindow, '', @SW_SHOW) WinSetState($oIE_google, '', @SW_SHOW) WinSetState($oIE_autoit, '', @SW_SHOW) ; inifinite event loop While 1 ; sleep for 100 milliseconds (to not hog the cpu) sleep(100) ; end of event loop WEnd Func CLOSEClicked() ; take care of things to do when exiting Winkill($hWndChild) Exit EndFunc Func WM_PAINT($hWnd, $Msg, $wParam, $lParam) Sleep(100) DllCall("user32.dll", "int", "InvalidateRect", "hwnd", $hWnd, "ptr", 0, "int", 0) EndFunc ;==>WM_PAINT ;=============================================================================== ; ; Function Name: _ProcessGetHWnd ; Description: Returns the HWND(s) owned by the specified process (PID only !). ; ; Parameter(s): $iPid - the owner-PID. ; $iOption - Optional : return/search methods : ; 0 - returns the HWND for the first non-titleless window. ; 1 - returns the HWND for the first found window (default). ; 2 - returns all HWNDs for all matches. ; ; $sTitle - Optional : the title to match (see notes). ; $iTimeout - Optional : timeout in msec (see notes) ; ; Return Value(s): On Success - returns the HWND (see below for method 2). ; $array[0][0] - number of HWNDs ; $array[x][0] - title ; $array[x][1] - HWND ; ; On Failure - returns 0 and sets @error to 1. ; ; Note(s): When a title is specified it will then only return the HWND to the titles ; matching that specific string. If no title is specified it will return as ; described by the option used. ; ; When using a timeout it's possible to use WinWaitDelay (Opt) to specify how ; often it should wait before attempting another time to get the HWND. ; ; ; Author(s): Helge ; ;=============================================================================== Func _ProcessGetHWnd($iPid, $iOption = 1, $sTitle = "", $iTimeout = 2000) Local $aReturn[1][1] = [[0]], $aWin, $hTimer = TimerInit() While 1 ; Get list of windows $aWin = WinList($sTitle) ; Searches thru all windows For $i = 1 To $aWin[0][0] ; Found a window owned by the given PID If $iPid = WinGetProcess($aWin[$i][1]) Then ; Option 0 or 1 used If $iOption = 1 OR ($iOption = 0 And $aWin[$i][0] <> "") Then Return $aWin[$i][1] ; Option 2 is used ElseIf $iOption = 2 Then ReDim $aReturn[UBound($aReturn) + 1][2] $aReturn[0][0] += 1 $aReturn[$aReturn[0][0]][0] = $aWin[$i][0] $aReturn[$aReturn[0][0]][1] = $aWin[$i][1] EndIf EndIf Next ; If option 2 is used and there was matches then the list is returned If $iOption = 2 And $aReturn[0][0] > 0 Then Return $aReturn ; If timed out then give up If TimerDiff($hTimer) > $iTimeout Then ExitLoop ; Waits before new attempt Sleep(Opt("WinWaitDelay")) WEnd ; No matches SetError(1) Return 0 EndFunc ;==>_ProcessGetHWnd $StaticTxt = ControlGetText("Embed Cmd","",1007) MsgBox(1,"Static Text", $StaticTxt) GUISetState() While GUIGetMsg() <> -3 WEnd  
    • Catalyst78
      By Catalyst78
      I want to be able to press one of the many extra buttons on my mouse to execute an autoit script function. To do this I have bound weird key combinations to to each button that would otherwise never be pressed, like shift+alt+ctrl+/ (see linked image and the following code.)
      Unfortunately this has a few annoying side effects, such as interfering with whatever I'm doing or one of the modifier keys occasionally getting 'stuck' down.
      I have been compling each version of this script directly into my startup folder(win7) and have been using it for years. But surely there is a better way of doing this, thanks for help in advance.

      http://prnt.sc/dquyar
      ;^ Ctrl ! Alt + Shift # Win HotKeySet("!{/}", "Back_Btn") ; spamclickoff HotKeySet("+!^{.}", "Forw_Btn") ; ___/Speakers/HeadPhones HotkeySet("+!^{,}", "Midd_Btn") ;MouseLock/InputStuff HotkeySet("+!^{\}", "Gs_Back_Btn") ;ScreenBrightness 100/60/20 HotkeySet("+!^{=}", "Gs_Forw_Btn") ;Vlc/CloseVlc Recent/Touhou HotkeySet("+!^{-}", "Gs_Midd_Btn") ;ScreenSwaper ToMain/ToSecond HotkeySet("+!^{]}", "Gs_M3") ;VlcTogglePlay HotkeySet("+!^{[}", "Gs_MW_Left") ;F11/!Enter  
×