User:Paolo Liberatore/Xexample.c

From Wikipedia, the free encyclopedia

/* Simple Xlib application that draws a box in a window and
 * terminate when the user presses a key. */

#include<X11/Xlib.h>

int main() {
  Display *d;
  int s;
  Window w;
  XEvent e;


/* open connection with the server; this will also generate
 * a request for creation of a default graphic context; it
 * may also generate a request for existence of some
 * extensions */

  d=XOpenDisplay(NULL);
  if(d==NULL) {
    printf("Cannot open display\n");
    exit(1);
  }
  s=DefaultScreen(d);

/* create a window; while the function returns the
 * identifier of a window, this identifier is actually
 * chosen by the library, which is part of the client, not
 * by the server */

  w=XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 100, 100, 1,
                        BlackPixel(d, s), WhitePixel(d, s));

/* select kind of events we are interested in; this will
 * generate a request for changing the window attributes */

  XSelectInput(d, w, ExposureMask | KeyPressMask);

/* request the window to be mapped (shown on the screen) */

  XMapWindow(d, w);

/* event loop (wait for event, take the appropriate action */

  while(1) {

/* this instruction checks for events in the local queue,
 * blocking if not event is present */

    XNextEvent(d, &e);

/* if the event is an expose event, redraw the box */

    if(e.type==Expose)
      XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10);

/* this particular client terminates if a key is pressed */

    if(e.type==KeyPress)
      break;
  }

/* close connection to server */

  XCloseDisplay(d);

  return 0;
}