Chapter 5. Event handling

Event 'macros'

wxPerl can't use static event tables for event handling, but the contructs it uses are similar to wxWindows ones; in particular wxPerl uses the same names for 'event macros'; the key differences are:

  • in wxPerl these are regular subroutines exported by the Wx::Event module
  • they take one additional first parameter: the Wx::EvtHandler object that must handle the event

so in a program you may use:

    package MyClass;

    # ....

    use Wx::Event qw(EVT_CLOSE EVT_BUTTON);

    sub new {
    
    # ......
        # pay attention to the additional parameter
        EVT_CLOSE( $this, \&OnClose );
        EVT_BUTTON( $this, $ID_MYBUTTON, \&OnClick );
    # .....

In wxPerl, if you do not need to know the id of a control (you will need it for FindWindow and similar functions) you may pass -1 to the constructor, and pass the object itself as the id (wxPerl will automatically do a GetId() on the object).

Event handlers and exceptions

Please note that event handlers are not exception safe. This means that if you die() (or croak() or confess() or even exit()) from an event handler, your program will most likely crash. Solution: don't do that, or if you are using exceptions, handle them in the handler:

  sub OnFoo {
      eval {
          # code that might die()
      };

      # log error (or handle it differently)
      Wx::LogError( $@ ) if $@;
  }

You might use the Error module for a more structured exception handling.