wxPython: binding wx.EVT_CHAR_HOOK disables TextCtrl backspace

2.6k views Asked by At

I have a wx.TextCtrl and I want to be able to type in it, but also detect key presses such as UP, DOWN, RETURN, ESC.

So I binded wx.EVT_KEY_DOWN to recognize any key press, and wx.EVT_CHAR_HOOK to do the same thing even when TextCtrl has focus.

self.Bind(wx.EVT_KEY_DOWN, self.keyPressed)
self.Bind(wx.EVT_CHAR_HOOK, self.keyPressed)

Key presses UP, DOWN, RETURN, ESC were recognized and working fine, but due to binding EVT_CHAR_HOOK I cannot use LEFT RIGHT BACKSPACE SHIFT anymore when I type in the TextCtrl.

Any suggestions?

1

There are 1 answers

2
Fenikso On BEST ANSWER

You should call event.Skip() at the end of the event handler to propagate it further. This works for me:

import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)
        self.text = wx.TextCtrl(self.panel)
        self.text.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.text.Bind(wx.EVT_KEY_UP, self.OnKeyUp)

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.text, 1)

        self.panel.SetSizerAndFit(self.sizer)  
        self.Show()

    def OnKeyDown(self, e):      
        code = e.GetKeyCode()
        if code == wx.WXK_ESCAPE:
            print("Escape")
        if code == wx.WXK_UP:
            print("Up")
        if code == wx.WXK_DOWN:
            print("Down")
        e.Skip()

    def OnKeyUp(self, e):
        code = e.GetKeyCode()
        if code == wx.WXK_RETURN:
            print("Return")
        e.Skip()


app = wx.App(False)
win = MainWindow(None)
app.MainLoop()