Xlib and GLX: Part 2

From Sidvind
Jump to: navigation, search

Catching the WM close-button[edit]

Code:

  1. /* Tell the window you want to recive the fscking event */
  2. Atom wm_delete_window = XInternAtom(GLWindow.dpy, "WM_DELETE_WINDOW", false);
  3. XSetWMProtocols(GLWindow.dpy, GLWindow.win, &GLWindow.wm_delete_window, 1);

Run that code any time after creating the window. Now you can catch the event ClientMessage in your event loop. When that event is caught you need to check if event.xclient.data.l[0] equals GLWindow.wm_delete_window.

Now, if just someone could have told me this instead of me having to dig through hundreds of lines of X code.

Getting keyboard input[edit]

First, make sure your window has been created with the KeyPressMask.

In your X Event look for the KeyPress event. The event.xkey struct contains enought info to be converted to an ascii character using XLookupString. XLookupString returns the numbers of characters written to the buffer. In this case a maximum of 1 can be written. If a non-printable character occurs the lenght will be 0. XLookupString also looks for key modifiers like shift and alt.

Code: glx2.c (view, download)

  1. static void poll(){
  2.         XEvent event;
  3.         while ( XPending(GLWindow.dpy) > 0 ){
  4.                 XNextEvent(GLWindow.dpy, &event);
  5.                 switch (event.type){
  6.                 case KeyPress:
  7.                 {
  8.                         char buf[2];
  9.                         int len;
  10.                         KeySym keysym_return;
  11.                         len = XLookupString(&event.xkey, buf, 1, &keysym_return, NULL);
  12.  
  13.                         if ( len != 0 ){
  14.                                 printf("Char: %c",buf[0]);
  15.                         }
  16.                 }
  17.                 break;
  18.  
  19.                 default:
  20.                         printf("Unhandled event: %d\n",event.type);
  21.                         break;
  22.                 }
  23.         }
  24. }