Re: [gtkmm] Getting key events?



Drinkin Park writes:
 >
 > How does one receive the keys that are being pressed/released from a 
 > GdkEventKey that is the parameter of an function called by a callback?

Your signal handler is blessed with a GdkEventKey * parameter.  The
struct it points to contains the information you're looking for:

Here's the struct's declaration (from gdk documentation):

struct GdkEventKey {

  GdkEventType type;
  GdkWindow *window;
  gint8 send_event;
  guint32 time;
  guint state;
  guint keyval;
  gint length;
  gchar *string;
  guint16 hardware_keycode;
  guint8 group;
};


the members you're probably most interested in:

guint keyval
the key that was pressed or released. See the <gdk/gdkkeysym.h> header file
for a complete list of GDK key codes.

GdkEventType type
the type of the event (GDK_KEY_PRESS or GDK_KEY_RELEASE)

guint state
a bit-mask representing the state of the modifier keys (e.g. Control, Shift
and Alt) and the pointer buttons. See GdkModifierType.



the gdkkeysym header file contains a bunch of #defines with
the codes you can compare keyval against:

#ifndef __GDK_KEYSYMS_H__
#define __GDK_KEYSYMS_H__

#define GDK_VoidSymbol 0xFFFFFF
#define GDK_BackSpace 0xFF08
#define GDK_Tab 0xFF09
#define GDK_Linefeed 0xFF0A
#define GDK_Clear 0xFF0B
....
#define GDK_5 0x035
#define GDK_6 0x036
....
#define GDK_A 0x041
#define GDK_B 0x042
#define GDK_C 0x043
#define GDK_D 0x044
....
#define GDK_c 0x063
#define GDK_d 0x064
#define GDK_e 0x065
#define GDK_f 0x066
....

#endif



so ... your signal handler might look something like this:


bool
SomeClass::OnKeyPress(GdkEventKey *evt)
{
    if (evt->keyval == GDK_a || evt->keyval == GDK_A)
        if (evt->state & GDK_CONTROL_MASK)
        {
            if (evt->type == GDK_KEY_PRESS)
                cout << "Ctrl-A pressed";
            else
                cout << "Ctrl-A released";

            // stop further processing of this event -
	    // we've handled it
            return true;
        }

    // this signal handler didn't do anything with the event
    // pass it on to the default (or other signal) handlers
    return false;
}


Note that the documentation warns that you should register for key event
notification on the widget whose signal you're connecting to.  If you don't
sign up for notification, you may just be attaching a handler to a signal
that's never emitted.  Use Gtk::Widget::add_events() or
Gtk::Widget::set_events() to register for notification:

widget.add_events(Gdk::KEY_PRESS_MASK | Gdk::KEY_RELEASE_MASK);

(you may have to cast this to Gdk::EventMask ...)


I haven't tested (or for that matter compiled this code) but it should get the
idea across. Fiddle around with it a bit - maybe even write evt's member
variables to cout to see what arrives as you mash those keys!



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]