Posted By

FArcellier on 08/06/11


Tagged

c GTK+


Versions (?)

Get Key information with GTK


 / Published in: C
 

  1. /*!
  2.  * \brief GTK Program to get information about key pressed
  3.  * \author Fabien Arcellier
  4.  *
  5.  * To compil with GTK : gcc -Wall `pkg-config --cflags gtk+-2.0` `pkg-config --libs gtk+-2.0` -o key_tool -g key_tool.c
  6.  */
  7. #include <gtk/gtk.h>
  8.  
  9. static void destroy (GtkWidget*, gpointer);
  10. static gboolean key_press_event (GtkWidget*, GdkEventKey*, gpointer);
  11.  
  12. int main(int argc, char *argv[])
  13. {
  14. GtkWidget *window = NULL, *label= NULL;
  15.  
  16. gtk_init(&argc, &argv);
  17.  
  18. window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
  19. gtk_window_set_title (GTK_WINDOW (window), "Key Pressed tool");
  20. gtk_container_set_border_width (GTK_CONTAINER (window), 10);
  21. gtk_widget_set_size_request (window, 300, 300);
  22. gtk_window_set_resizable (GTK_WINDOW (window), FALSE);
  23.  
  24. label = gtk_label_new ("Press a key");
  25. gtk_label_set_selectable (GTK_LABEL (label), TRUE);
  26.  
  27. gtk_container_add (GTK_CONTAINER (window), label);
  28. gtk_widget_show_all (window);
  29.  
  30. g_signal_connect (G_OBJECT (window), "key_press_event", G_CALLBACK (key_press_event), NULL);
  31. g_signal_connect (G_OBJECT (window), "destroy", G_CALLBACK (destroy), NULL);
  32.  
  33. gtk_main();
  34. return 0;
  35. }
  36.  
  37. /*!
  38.  * \brief Close application
  39.  */
  40. static void destroy (GtkWidget *window, gpointer data)
  41. {
  42. gtk_main_quit();
  43. }
  44.  
  45. /*!
  46.  * \brief Display information about key pressed in label
  47.  */
  48. static gboolean key_press_event(GtkWidget *window, GdkEventKey *event, gpointer data)
  49. {
  50. char key_event_info[1024] = "";
  51. char *event_string = NULL;
  52. GtkWidget *label = NULL;
  53.  
  54. if (event -> string != NULL)
  55. {
  56. event_string = event -> string;
  57. }
  58. else
  59. {
  60. *event_string = '\0';
  61. }
  62.  
  63. sprintf(key_event_info, "Key\n\n \
  64. send_event : %d\n \
  65. time : %d \n \
  66. state : %d \n \
  67. keyval : %d \n \
  68. length : %d \n \
  69. string : %s \n \
  70. hardware_keycode : %d \n \
  71. group : %d \n \
  72. is_modifier %d",
  73. event -> send_event,
  74. event -> time,
  75. event -> state,
  76. event -> keyval,
  77. event -> length,
  78. event_string,
  79. event -> hardware_keycode,
  80. event -> group,
  81. event -> is_modifier
  82. );
  83.  
  84. label = gtk_bin_get_child (GTK_BIN (window));
  85. gtk_label_set_text (GTK_LABEL (label), key_event_info);
  86.  
  87. return TRUE;
  88. }

Report this snippet  

You need to login to post a comment.