Reputation: 1
We're trying to filter keys in the key press event in C using glade. But we can't figure out how to filter those keys. Here is the code:
// called when key pressed
void on_window_main_key_press_event()
{
}
Upvotes: 0
Views: 2069
Reputation: 9331
You have to use GdkEventKey
to handle key press events.
The struct looks like this:
struct GdkEventKey {
GdkEventType type; // is it a key-press or key release event
GdkWindow *window; // the window receiving the event
gint8 send_event; // whether the event was sent explicitly. It's TRUE in that case
guint32 time; //time of event in ms
guint state; //a bit mask representing state of (Ctrl/Alt/Shift)
guint keyval; // the key that was pressed
gint length; // length of string
gchar *string; //the string that may result from this kepress
guint16 hardware_keycode; //hardware key code
guint8 group; // keyboard group
guint is_modifier : 1; //whether the key is mapped as modifier
};
You can find the values of all key presses in this file: gdkkeysyms.h
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
gboolean
on_window_main_key_press_event (GtkWidget *widget, GdkEventKey *event, gpointer user_data);
int main (int argc, char *argv[])
{
GtkWidget *window;
gtk_init (&argc, &argv);
window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
g_signal_connect (G_OBJECT (window), "key_press_event", G_CALLBACK (on_window_main_key_press_event), NULL);
gtk_widget_show_all (window);
gtk_main ();
return 0;
}
gboolean
on_key_press (GtkWidget *widget, GdkEventKey *event, gpointer user_data)
{
switch (event->keyval)
{
case GDK_Z:
case GDK_z:
printf("key pressed: %s\n", "Z");
break;
case GDK_S
case GDK_s:
if (event->state & GDK_SHIFT_MASK)
{
printf("key pressed: %s\n", "shift + s");
}
else if (event->state & GDK_CONTROL_MASK)
{
printf("key pressed: %s\n", "ctrl + s");
}
else
{
printf("key pressed: %s\n", "s");
}
break;
default:
return FALSE;
}
return FALSE;
}
Upvotes: 2
Reputation:
I think this should help you
void on_window_main_key_press_event(GtkWidget *widget, GdkEventKey *key, gpointer user_data) {
int TheKeyThatWasPressed = key->keyval; //Incase you need to find out what key got pressed
}
Then use this in your main function:
g_signal_connect(Window, "key-press-event", G_CALLBACK(KeyPressHandler), NULL);
Upvotes: 0
Reputation: 694
the callback function for keypress is
on_key_press(GtkWidget *widget, GdkEventKey *key, gpointer user_data)
GdkEventKey structure is defined here (https://developer.gnome.org/gdk3/stable/gdk3-Event-Structures.html#GdkEventKey) and keyval returns the value of the key pressed you can compare it like this.
strcmp(gdk_keyval_name(key->keyval), "Return") == 0
Upvotes: 2