Site hosted by Angelfire.com: Build your free website today!

Hands-on Projects for the Linux Graphics Subsystem

New book from Christos Karayiannis

Available in Amazon Kindle format at:

amazon.com   amazon.co.uk   amazon.de   amazon.es   amazon.fr   amazon.it

Xlib examples

Next we present some Xlib examples:

Example 1

The first example comes from Wikipedia (another version of the same program is found here). It creates a window with a little black square in it:


 /*
   Simple Xlib application drawing a box in a window.
   gcc input.c -o output -lX11
 */
 #include <X11/Xlib.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
 int main(void) {
   Display *d;
   Window w;
   XEvent e;
   char *msg = "Hello, World!";
   int s;
 
                        /* open connection with the server */
   d = XOpenDisplay(NULL);
   if (d == NULL) {
     fprintf(stderr, "Cannot open display\n");
     exit(1);
   }
 
   s = DefaultScreen(d);
 
                        /* create window */
   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 */
   XSelectInput(d, w, ExposureMask | KeyPressMask);
 
                        /* map (show) the window */
   XMapWindow(d, w);
 
                        /* event loop */
   while (1) {
     XNextEvent(d, &e);
                        /* draw or redraw the window */
     if (e.type == Expose) {
       XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10);
       XDrawString(d, w, DefaultGC(d, s), 50, 50, msg, strlen(msg));
     }
                        /* exit on key press */
     if (e.type == KeyPress)
       break;
   }
 
                        /* close connection to server */
   XCloseDisplay(d);
 
   return 0;
 }

This example uses two Xlib routines XOpenDisplay() and XCreateSimpleWindow() to connect to the X server and then to create a window. Then it calls XMapWindow() to make the window visible on the screen. What is important here is that until XFlush() is called the previous requests do not arrive to the server.

Example 2

Another example comes from the Beginner Xlib Tutorial:


#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include <X11/Xos.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>

Display *dis;
Window win;

int main() {
dis = XOpenDisplay(NULL);
win = XCreateSimpleWindow(dis, RootWindow(dis, 0), 1, 1, 500, 500, \
0, BlackPixel (dis, 0), BlackPixel(dis, 0));
XMapWindow(dis, win);
XFlush(dis);
/*Sleep 5 seconds before closing.*/
sleep(5);
return(0);
}

Other recommended tutorials:
Anatomy of the most basic Xlib program
http://nobug.ifrance.com/nobug2/article1/babyloon/tut_xwin.htm