Jump to content
vindicta

Help Needed with GUISetAccelerators

Recommended Posts

vindicta

Hello everyone,

I am trying to setup a GUI accelerator to close the utility as soon as esc is pressed.  It works fine with hotkey but I want to make sure that the utility only exits if its window was active when esc was pressed. My utility has 2 buttons, Backup and Restore.

The exit function checks if the button clicked was Backup or Restore and then displays an error message accordingly.

If pressed backup, $button = 1

if pressed restore, $button = 2

the value of $button is set inside backup() or restore() functions

Opt("GUIOnEventMode", 1)
Opt("GUICoordMode", 1)

$Form1 = GUICreate("Form1", 419, 124, 238, 194, $WS_DLGFRAME)
$B_backup = GUICtrlCreateButton("Backup", 48, 40, 145, 41)
$B_restore = GUICtrlCreateButton("Restore", 224, 40, 145, 41)

;================ > HotKeySet('{ESC}', "terminate")
GUICtrlSetOnEvent($B_backup, "Backup")
GUICtrlSetOnEvent($B_restore, "Restore")
GUISetState(@SW_SHOW)
Dim $accelKey[1][2] = [["{ESC}", terminate()]]
GUISetAccelerators($accelKey)

While 1
    Switch GUIGetMsg()
        Case $GUI_EVENT_CLOSE
            Exit
    EndSwitch
WEnd

 

Exit function:

func terminate()
Do
    $msg = GUIGetMsg()
Until $msg <> 0

While 1
        If $button = 1 Then
            ProcessClose("robocopy.exe")
            MsgBox(16, "Abort!", "Backup Aborted!")
            exit
        ElseIf $button = 2 Then
            ProcessClose("robocopy.exe")
            MsgBox(16, "Abort!", "Restore Aborted!")
            exit
        Else
            While 1
                For $i = 3 To 1 Step -1
                    SplashTextOn("Closing Utility...", $i, 130, 54, -1, -1, 0, "Calibri", "", 900)
                    Sleep(1000)
                Next
                ExitLoop
            WEnd
            SplashOff()
            Exit
        Endif
WEnd

What am I doing wrong here? The utility closes as soon as it launches with Splash text.

Edited by vindicta
missing endif added.

Share this post


Link to post
Share on other sites
BrewManNH

Accelerator keys work on controls, not on functions. You have to create a control for it to action, and a function associated with that control. Something like this,

$id_Dummy = GUICtrlCreateDummy() ; <<<<<<<<<<<<<<<<<<<<
GUICtrlSetOnEvent($id_Dummy, "terminate") ; <<<<<<<<<<<<<<<<<<<<
;================ > HotKeySet('{ESC}', "terminate")
GUICtrlSetOnEvent($B_backup, "Backup")
GUICtrlSetOnEvent($B_restore, "Restore")
GUISetState(@SW_SHOW)
Dim $accelKey[1][2] = [["{ESC}", $id_Dummy] ; <<<<<<<<<<<<<<<<
GUISetAccelerators($accelKey)

 

  • Like 2

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites
vindicta

Thank you for this simple tutorial. Helped me understand accelerators better. One more question I have is that HotKey allowed me to exit right away, regardless of what the program was doing. I am assuming that it is not possible to do so with Accelerators? I ran backup function and hit the ESC key, nothing happened. I assumed it was waiting for copy to finish before it can run the exit function? If that's the case, is HotKey my only way out?

  • Like 1

Share this post


Link to post
Share on other sites
vindicta

While Using HotKey to exit, I added an extra if statement to confirm that the ESC was really pressed to exit the utility. This gives me at least a chance to continue with the backup/restore if I want to.

function terminate()
While 1
    If MsgBox(36, "", "You pressed ESC" & @CRLF & "Do you want to abort the operation?") = 6 Then
        If $button = 1 Then
            ProcessClose("robocopy.exe")
            MsgBox(16, "Abort!", "Backup Aborted!")
            Exit
        ElseIf $button = 2 Then
            ProcessClose("robocopy.exe")
            MsgBox(16, "Abort!", "Restore Aborted!")
            Exit
        Else
            While 1
                For $i = 3 To 1 Step -1
                    SplashTextOn("Closing Utility...", $i, 130, 54, -1, -1, 0, "Calibri", "", 900)
                    Sleep(1000)
                Next
                ExitLoop
            WEnd
            SplashOff()
            Exit
        EndIf
    Else
            Sleep(10)
            ExitLoop
    EndIf
Wend
Endfunc

Would still love to know if this can be achieved any other way.

Edited by vindicta

Share this post


Link to post
Share on other sites
BetaLeaf

Your confirm exit function could use some work. See this example.

#include <MsgBoxConstants.au3>
Global $ubound = 5 * @DesktopRefresh
_Init()
Func _Init()
    ProgressOn("Pretending to do some work.", "", "This is an example script. Press esc to exit.")
    HotKeySet("{esc}", "_ConfirmExit")
EndFunc   ;==>_Init
While 1
    For $i = 1 To $ubound
        ProgressSet($i / $ubound * 100)
        Sleep(1000 / @DesktopRefresh)
    Next
    Sleep(550)
WEnd
Func _ConfirmExit()
    HotKeySet("{esc}")
    ProgressOff()
    If MsgBox(BitOR($MB_YESNO, $MB_SETFOREGROUND), @ScriptName, "Are you sure you want to exit?") = $IDYES Then
        Exit
    Else
        _Init()
    EndIf
EndFunc   ;==>_ConfirmExit

 

  • Like 1

False Positive Reporter - Mass email all anti virus vendors with an attachment of your program for fast and easy whitelisting.

PortableApps.com App Creation Wizard  - A simple GUI-based Wizard for creating PortableApps.

SoundBoard - Play any song or sound you want at the press of a hotkey.

My GitHub Page: https://github.com/BetaLeaf

Share this post


Link to post
Share on other sites
vindicta
1 hour ago, BetaLeaf said:

Your confirm exit function could use some work. See this example.

#include <MsgBoxConstants.au3>
Global $ubound = 5 * @DesktopRefresh
_Init()
Func _Init()
    ProgressOn("Pretending to do some work.", "", "This is an example script. Press esc to exit.")
    HotKeySet("{esc}", "_ConfirmExit")
EndFunc   ;==>_Init
While 1
    For $i = 1 To $ubound
        ProgressSet($i / $ubound * 100)
        Sleep(1000 / @DesktopRefresh)
    Next
    Sleep(550)
WEnd
Func _ConfirmExit()
    HotKeySet("{esc}")
    ProgressOff()
    If MsgBox(BitOR($MB_YESNO, $MB_SETFOREGROUND), @ScriptName, "Are you sure you want to exit?") = $IDYES Then
        Exit
    Else
        _Init()
    EndIf
EndFunc   ;==>_ConfirmExit

 

Thank you for improving on this. :thumbsup:
I am really a noob programmer and just stepping into creating automated utilities. I will try to figure out how all this is working and try to make it work with my rest of the script.
Thanks again!

Edited by vindicta

Share this post


Link to post
Share on other sites
BetaLeaf

I just optimized the confirm exit. _init() was simply a way to reuse code efficiently. 


False Positive Reporter - Mass email all anti virus vendors with an attachment of your program for fast and easy whitelisting.

PortableApps.com App Creation Wizard  - A simple GUI-based Wizard for creating PortableApps.

SoundBoard - Play any song or sound you want at the press of a hotkey.

My GitHub Page: https://github.com/BetaLeaf

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

  • Similar Content

    • therks
      By therks
      So I'm working on an application and I've hot keyed all the numbers, and for some reason this particular combination doesn't work. All the other numbers with Ctrl+Shift work fine, and all other combinations of modifiers work with 0. Has anyone else encountered this? It's very strange. 
      Guicreate('', 300, 300) $button = GUICtrlCreateButton('Button', 0, 0) Dim $accel = [ [ '^+0', $button ] ] GUIsetaccelerators($accel) Do $gm = guigetmsg()  If $gm = $button then msgbox(0,'','test') Until $gm = - 3 Sorry for the ugly code, i typed this up on my phone. 😅
    • guner7
      By guner7
      Hi everyone,
      I would like to share a simple snippet where I use for my hotkey script.
      I was searching for a solution whereby pressing a same key, I could have different outcome according to the way the key is being pressed.
      1) Double tap/press fast (like double click the mouse) - outcome A
      2) Long press or HOLD for awhile (2-4 sec) - outcome B
      #Include <Timers.au3> Global $interval_timer, $counter HotKeySet("{F10}", "_terminate") While 1 Sleep(10) WEnd Func _terminate() Local $itv_timer $itv_timer = _Timer_Diff($interval_timer) $interval_timer = _Timer_Init() ;ConsoleWrite($itv_timer & @CRLF) ;to review the timer difference so I can decide the range to capture double tap sequence If $itv_timer > 100 And $itv_timer < 250 Then $counter = 0 $interval_timer = _Timer_Init() MsgBox("","","double tap detected") Elseif $counter >= 25 Then $counter = 0 $interval_timer = _Timer_Init() MsgBox("","","long press detected") ElseIf $itv_timer < 50 Then $counter = $counter + 1 ConsoleWrite($counter & @CRLF) Else $counter = 0 EndIf EndFunc The trick here is to collect and use the frequency of the hotkey is called, and the time difference between each time the hotkey is being called.
      My coding style is not efficient and can be such a mess most of the time, any suggestion or better coding are welcome.
      I hope you find this one helpful.
    • AndyS19
      By AndyS19
      I have a script that traps ^A and ^C accelerator keys via the GUISetAccelerators() function, and in the key handlers, I check to see if the focus is on the control that I want the keys to operate on.
      However, when I see that I'm not on that control, I want to pass the ^C and ^A back to the system so I can copy and past data on other controls.
      Here is my test script.  I have it applying ^A and ^C only to the ListView control.  When I put focus on the Input control, I want to be able to copy and paste normally.
      Opt("GUICloseOnESC", 1) ; ESC does not close the GUI Opt("GUIOnEventMode", 1) ; Change to OnEvent mode Opt('MustDeclareVars', 1) OnAutoItExitRegister("ExitStageLeft") #include <Array.au3> #include <GuiListBox.au3> #include <GUIConstantsEx.au3> #include <ListBoxConstants.au3> #include <WindowsConstants.au3> #include <GuiListView.au3> Global $hGUI, $iInput, $iList, $hInput, $hList _Main() Func _Main() Local $str, $parts $hGUI = GUICreate("", 250, 500) $iInput = GUICtrlCreateInput("2", 90, 5, 50, 20) $hInput = GUICtrlGetHandle($iInput) $iList = GUICtrlCreateListView("First Column ", 5, 30, 240, 470, $LBS_EXTENDEDSEL) $hList = GUICtrlGetHandle($iList) For $ndx = 1 To 100 $str = StringFormat("%s ABC", $ndx) Local $ret = _GUICtrlListView_AddItem($hList, $str) Next setupSpecialKeysHandlers() GUISetOnEvent($GUI_EVENT_CLOSE, "ExitStageLeft") GUISetState(@SW_SHOW) While (1) Sleep(250) WEnd EndFunc ;==>_Main Func ExitStageLeft() Exit (1) EndFunc ;==>ExitStageLeft Func setupSpecialKeysHandlers() Local $aAccelKeys[1][2] Local $ar, $parts, $key, $handler, $id ; Create a table of Special keys and their handlers $ar = StringSplit("", "") _ArrayAdd($ar, "{ENTER} - handle_ENTER_key ") _ArrayAdd($ar, "^a - handle_CTRL_A_key ") _ArrayAdd($ar, "^c - handle_CTRL_C_key ") ReDim $aAccelKeys[UBound($ar) - 1][2] ; Now, create $aAccelKeys array with the table data. ; For each entry, create a Dummy GUI and associate its ; ID with the special key. For $ndx = 1 To UBound($ar) - 1 $parts = StringSplit($ar[$ndx], "-", 2) $key = StringStripWS($parts[0], 8) $handler = StringStripWS($parts[1], 8) $id = GUICtrlCreateDummy() $aAccelKeys[$ndx - 1][0] = $key $aAccelKeys[$ndx - 1][1] = $id GUICtrlSetOnEvent($id, $handler) Next ; Dump the contents of the $aAccelKeys array For $ndx = 0 To UBound($aAccelKeys) - 1 logMsg("$aAccelKeys" _ & " [" & $ndx & "][0] = " & StringFormat("%-8s", $aAccelKeys[$ndx][0]) _ & " [" & $ndx & "][1] = " & $aAccelKeys[$ndx][1]) Next GUISetAccelerators($aAccelKeys) ; Setup the Special keys hooks EndFunc ;==>setupSpecialKeysHandlers Func logMsg($msg, $lnum = @ScriptLineNumber) ConsoleWrite("+++:" & $lnum & ": " & $msg & @CRLF) EndFunc ;==>logMsg Func handle_ENTER_key() logMsg("+++: handle_ENTER_key() entered") EndFunc ;==>handle_ENTER_key Func handle_CTRL_A_key() logMsg("+++: handle_CTRL_A_key() entered") If (Not isCtrlFocused($hList)) Then Return selectAllGLVItems() EndFunc ;==>handle_CTRL_A_key Func handle_CTRL_C_key() logMsg("+++: handle_CTRL_C_key() entered") If (isCtrlFocused($hList)) Then extractSelListViewGamesToClip() Else EndIf EndFunc ;==>handle_CTRL_C_key Func isCtrlFocused($hWnd) Local $hCtrl $hCtrl = ControlGetHandle($hGUI, "", ControlGetFocus($hGUI)) Return ($hWnd = $hCtrl) ? True : False EndFunc ;==>isCtrlFocused Func selectAllGLVItems() Local $hWnd = $hList, $iIndex For $iIndex = 0 To _GUICtrlListView_GetItemCount($hWnd) _GUICtrlListView_SetItemSelected($hWnd, $iIndex) Next EndFunc ;==>selectAllGLVItems Func extractSelListViewGamesToClip() Local $hWnd = $hList Local $iIndex, $item, $str, $sep = "" $str = "" For $iIndex = 0 To _GUICtrlListView_GetItemCount($hWnd) If (_GUICtrlListView_GetItemSelected($hWnd, $iIndex)) Then $item = _GUICtrlListView_GetItemText($hWnd, $iIndex) $str &= $sep & $item $sep = @CRLF EndIf Next ClipPut($str) logMsg("Copied " & StringLen($str) & " bytes to the Clipboard:" & @CRLF & $str) EndFunc ;==>extractSelListViewGamesToClip  
    • John C.
      By John C.
      ;Adding $BS_DEFPUSHBUTTON doesn't work
              $idCopy_Data = GUICtrlCreateButton("Copy Data Only", $iButtonWidth_2, $aiGUISize[1] - $iButtonMargin, $iButtonWidth_2, 20, $BS_DEFPUSHBUTTON)
      ;Adding these two lines doesn't work either
               Local $aAccelKeys[2][2] = [["{enter}", $idCopy_Data], ["^{enter}", $idCopy_ID]]
              GUISetAccelerators($aAccelKeys)
       
×