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

    • 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!
    • TheOnlyOne
      By TheOnlyOne
      So currently I have some code waiting for a status to change(there is different indicators to check if this status has changed) 
      Func oneRow($count) $globaltimer = _Timer_SetTimer($gui, 60000*10, "reset") $errTimer = TimerInit() While (1)         If PixelGetColor(1117, 326) = 0xC6C6C6 Then ExitLoop (1)         Sleep(500)         MouseClick("right")         Sleep(600)         If PixelGetColor(1117, 326) = 0xC6C6C6 Then ExitLoop (1)         If TimerDiff($errTimer) > 5000 Then             If PixelGetColor(1100, 310) = 0x707070 Or PixelGetColor(901, 305) = 0xE0E0E0 Or PixelGetColor(1043, 383) = 0xC6C6C6 Then                 Sleep(100)                 Send("{esc}")                 Sleep(1000)             EndIf         EndIf     WEnd .... EndFunc   ;==>oneRow The two timers is for error checking. This works just fine the problem comes when I go into the while 1 loop, my hotkeys at the top of the program seems to stop working, for an example 
      HotKeySet("{f1}", "stop") Func stop() Exit EndFunc ;==>stop Does not work at all after the while loop. The globaltimer is never called even though i tried setting the delay all the way down to 3 seconds. So I thought that maybe one of the function I use is blocking so the timer would never be called/the hotkey wouldn't work? if i make an delay just before the while loop the hotkey works just fine. Oh and the errTimer is supossed to not reset after 5 seconds but should keep making the check it does if five seconds have passed
    • Skysnake
      By Skysnake
      Hi All
      Question, the Help file contains this:
      So, is it necessary to put 
      GUISetAccelerators(0) ; Remove accelerator link in the GUI?  Once the GUI is deleted, the Accelerators are gone...?
      Enter like tab discussion contains this item.  Is it essential?
    • RobOtter
      By RobOtter
      Hi,
      is there a function or a UDF for parsing a hotkey definition string like "^a" or "+!{F1}" ?
      I´d like to create a settings GUI where users are able to define their custom hotkeys for a specific function and then save it to an ini. Of course, at the next start of the program, these settings have to read and not only the HotkeySet() command needs to be fed with it but also the settings GUI.
      As I do not want to present the user just the hotkey string but a rather user-friendly display (like checkboxes for the separate modifier keys and a drop down list of supported trigger keys), I need to fiddle on the saved string.
      I would envision a function that takes a hotkey string and returns for example an array like this: [isCtrl][isAlt][isShift][isWin][triggerKey][isTriggerVirtual]. And of course, there needs to be a function decoding the array back to the respective string representation.
       
      Thanks for your hints!