Jump to content

Menus with Shortcuts: Solution


Recommended Posts

#include <GUIConstants.au3>
#include "Hotkeys.au3"


; Step 1. create GUI.
$gui = GUICreate("Menu Hotkey Demo")
$mnuFile = GUICtrlCreateMenu("&File")
$mnuFileNew = GUICtrlCreateMenuItem("&New" & @TAB & "Ctrl+N",$mnuFile)
$mnuFileOpen = GUICtrlCreateMenuItem("&Open" & @TAB & "Ctrl+O",$mnuFile)
$mnuFileSave = GUICtrlCreateMenuItem("&Save" & @TAB & "Ctrl+S", $mnuFile)
GUICtrlCreateMenuItem("",$mnuFile)
$mnuFileExit = GUICtrlCreateMenuItem("E&xit" & @TAB & "Alt+F4", $mnuFile)
$mnuEdit = GUICtrlCreateMenu("&Edit")
$mnuEditSelectAll = GUICtrlCreateMenuItem("Select &All" & @TAB & "Ctrl+A", $mnuEdit)

GUISetState()

; Step 2. Define hotkeys. Each hotkey pairs with a function.
; $hotkeys is the only one that can be used.
$hotkeys = "^n,newfile,^o,openfile,^s,savefile,^a,selectall"

; Step 3. Window loop
While 1
    checkHotKeys($gui)
    
    $msg = GUIGetMsg()
    Switch $msg
        Case $mnuFileNew
            newfile()
        Case $mnuFileOpen
            openfile()
        Case $mnuFileSave
            savefile()
        Case $mnuEditSelectAll
            selectall()
        Case $GUI_EVENT_CLOSE, $mnuFileExit
            exitprogram()
        Case Else
    EndSwitch
WEnd

; Step 4. Define functions
Func newfile()
    MsgBox(0,"Event","New File")
EndFunc

Func openfile()
    MsgBox(0,"Event","Open File")
EndFunc

func savefile()
    MsgBox(0,"Event","Save File")
EndFunc

Func selectall()
    MsgBox(0,"Event","Select All")
EndFunc

Func exitprogram()
    MsgBox(0,"Event","Exit")
    Exit
EndFunc

Hotkeys.au3

;; Hotkey-related functions.
;; Define and undefine hotkeys here.

$hks = "nodef"

Func checkHotKeys($win)
    If WinActive($win)      Then setHotkeys(1)
    If WinActive($win) = 0  Then setHotkeys(0)
EndFunc
    

Func setHotkeys($value)
    $hks = StringSplit($hotkeys, ",")
    For $i = 1 to $hks[0] Step 2
        If $value = 1 Then HotKeySet($hks[$i],"runfunc")
        If $value = 0 Then HotKeySet($hks[$i])
    Next
EndFunc

Func runfunc()
    setHotkeys(0)
    $hks = StringSplit($hotkeys, ",")
    For $i = 1 to $hks[0] Step 2
        If @HotKeyPressed = $hks[$i] Then
            Call($hks[$i+1])
        EndIf
    Next
    setHotkeys(1)
EndFunc
Edited by RobertKipling
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...