John A - Essex
John A - Essex

Reputation: 1

Preventing f10 selecting the menu bar in Python (Windows 10/11)

I admit that ideally I should not be trying to use the f10 as a keypress() in python but I have a program which is used at a miniature railway to track train movements. The signallers select the type of train entering the system using the f keys (1-12) because that is what the visual basic predecessor did.

The program works fine, all of the f keys call a listener piece of code but when f10 is pressed the code freezes and (from googling) I think windows is switching focus to the python application menu bar. Pressing f10 again (or pretty much any key) resumes the program including running the code I set for f10 (irrespective of whether it is f10 pressed twice or another key).

I have tried return "break" but it appears that the menubar is being processed before the keystroke is passed to python and the listener.

def on_release(key): # process to process key strokes based on when key is released
    lastkey=format(key) # format the key released to make it easier to process
    if lastkey[:4]=="Key.": # Test special keys
        lastkey=lastkey[4:] # strip off first 4 characters
        match lastkey:
            case "f10":
                btemp=berth[1][0:2] # read contents of CH11
                if btemp != "2H":
                    ntemp=nextcode[6]+100 # get new number
                    ntemp=str(ntemp)
                    i=0
                    while i<6: # Look through stack for headcode 2H
                        if chstack[i][0:2]=="2H":
                            ntemp=chstack[i][-2:] # store number from headcode
                            j=i
                            while j<5:
                                chstack[j]=chstack[j+1] # move entries down stack
                                j=j+1
                            chstack[5]="    " # blank end of stack
                            i=7
                        i=i+1
                    ntemp="2H"+ntemp[-2:] # create new headcode
                    if i==6:
                        nextcode[6]=nextcode[6]+1 # increase next number
                        if (nextcode[6]>99): # loop next number when reaches 100
                            nextcode[6]=1
                    berth[1]=ntemp # store new headcode in CH11
                return "break"


def on_press(key): # routine to catch key presses (no action taken)
    return "break"

# Set up listener event to asynchronously process key strokes
listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release)
listener.start()


Any help gratefully received

I have tried using both the laptop keyboard and an external keyboard.

Upvotes: 0

Views: 37

Answers (0)

Related Questions