vindicta

Help Needed with GUISetAccelerators

7 posts in this topic

#1 ·  Posted (edited)

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

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)

 

2 people like this

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

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?

1 person likes this

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

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

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

 

1 person likes this

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

#6 ·  Posted (edited)

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

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

    • 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)
       
    • Xandy
      By Xandy
      Screenshot program that can upload/FTP to website/storage with hotkey.
      Features GUI to display programmable keys.

      Set the hotkeys with this function to use, and display hotkeys.
      ; hotkey_set() Parameters: ; ----------------------------------------------------------- ; $aHotkey -                The array hotkeys are stored in. This function sets the values of this array[hotkey_id][$hotkey_data] ; $dHotkey_id -             The enum for this hotkey index ; $sHotkey_description -     The label displayed to the user to represent function of hotkey ; $sHotkey_name -            The hotkey it'self.  Whatever name string you want to give the key ; $dHotkey_key -             The _IsPressed keycode ;    Keycodes AT: https://www.autoitscript.com/autoit3/docs/libfunctions/_IsPressed.htm ; $dHotkey_shift -             Shift flag 0 or 1 Default off ; $dHotkey_ctrl -             Ctrl flag 0 or 1 Default off ; $dHotkey_alt -             Alt flag 0 or 1 Default off Func hotkey_set(ByRef $aHotkey, $dHotkey_id, $sHotkey_description, $sHotkey_name, $dHotkey_key, $dHotkey_shift = 0, $dHotkey_ctrl = 0, $dHotkey_alt = 0)     $aHotkey[$dHotkey_id][$eHotkey_data_key_description] = $sHotkey_description     $aHotkey[$dHotkey_id][$eHotkey_data_key_name] = $sHotkey_name     $aHotkey[$dHotkey_id][$eHotkey_data_key] = $dHotkey_key     $aHotkey[$dHotkey_id][$eHotkey_data_shift] = $dHotkey_shift     $aHotkey[$dHotkey_id][$eHotkey_data_ctrl] = $dHotkey_ctrl     $aHotkey[$dHotkey_id][$eHotkey_data_alt] = $dHotkey_alt EndFunc   ;==>hotkey_set ; You can set your hotkeys here ; Please visit the hotkey_set() function for parameter information hotkey_set($aHotkey, $eHotkey_screenshot_ftp, "Selected Window to FTP", "F12", "7B", 0, 1, 0); F12 hotkey_set($aHotkey, $eHotkey_screenshot_disk, "Selected Window to Disk", "S", "53", 1, 1, 1); S hotkey_set($aHotkey, $eHotkey_clipboard_send, "Send Clipboard keystrokes", "F10", "79", 1, 1, 1); F10  
      Configure settings dialog:

      Screenshot Filename and Screenshot Counter, are used to create simple unique filenames that can cycle. Copy URL to clipboard option. - For linking your screenshots. The screenshot file type is for local copy only. App always uses .JPG for FTP right now, but I could add FTP screenshot file type specification.  
      Any suggestions?  Did I break anything, what did I miss?
      Package uses TTS.au3 by Beege: 
       
      FTP_Screen.zip
      File includes:
         - FTP_Screen.au3
         - FTPScreen.ico
         - TTS.au3 - by Beege
    • WoodGrain
      By WoodGrain
      Hi All,
      Could someone please PLEASE tell me what I'm doing wrong here?
      I feel like I'm close to figuring this out, I think I've identified what is causing the issue.
      Whenever I try to use the hotkey CTRL+SHIFT+T (or any other letter other than T for that matter) to paste the text to notepad, my CTRL and SHIFT keys are held down *IF* I release them *WHILE* the raw text is being written.
      It seems to be that if I release the CTRL+SHIFT keys:
      Before the Send Raw text starts to write to the screen: the CTRL and SHIFT keys ARE NOT held down, this is good During the Send Raw text being written to the screen: the CTRL and SHIFT keys ARE held down perpetually until I physically press them on the keyboard, this is bad After the Send Raw text has written all text to the screen: the CTRL and SHIFT keys ARE NOT held down, this is good This is also the case if I were to use the Windows Key as the hot key instead of the CTRL+SHIFT, I would need to tap the WIN key physically on my keyboard if I released it while the raw tet was being sent to the screen (eg, WIN+T).
      This issue also happens no matter which program I try to write the text to.
      Here's some example code:
      (I've put a bunch of "a's" in there to give enough time to test releasing the CTRL+SHIFT before/during/after the writing of them)
      HotKeySet("^+t", "WriteTxt") Func WriteTxt() WinWaitActive("Untitled - Notepad") $var = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" send($var, 1) EndFunc While 1 Sleep(500) WEnd Thanks guys!