Xlib tutorial part 1 -- Beginnings

by Alan at Mon 12th Jan 2009 12:59AM EST
updated Sat 24th Jan 2009 6:35PM EST


And welcome to my X11 xlib tutorial.

Most tutorials seem to start off with a bunch of discussion of client/server and how X seems to mess up your head. Instead, I'm going to start with one of the simplest possible X programs. Put a blank window on the screen.

/* first include the standard headers that we're likely to need */
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xresource.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char ** argv){
	int screen_num, width, height;
	unsigned long background, border;
	Window win;
	XEvent ev;
	Display *dpy;

	/* First connect to the display server, as specified in the DISPLAY 
	environment variable. */
	dpy = XOpenDisplay(NULL);
	if (!dpy) {fprintf(stderr, "unable to connect to display
");return 7;}

	/* these are macros that pull useful data out of the display object */
	/* we use these bits of info enough to want them in their own variables */
	screen_num = DefaultScreen(dpy);
	background = BlackPixel(dpy, screen_num);
	border = WhitePixel(dpy, screen_num);

	width = 40; /* start with a small window */
	height = 40;

	win = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), /* display, parent */
		0,0, /* x, y: the window manager will place the window elsewhere */
		width, height, /* width, height */
		2, border, /* border width & colour, unless you have a window manager */
		background); /* background colour */

	/* tell the display server what kind of events we would like to see */
	XSelectInput(dpy, win, ButtonPressMask|StructureNotifyMask );

	/* okay, put the window on the screen, please */
	XMapWindow(dpy, win);

	/* as each event that we asked about occurs, we respond.  In this
	 * case we note if the window's shape changed, and exit if a button
	 * is pressed inside the window */
		XNextEvent(dpy, &ev);
		case ConfigureNotify:
			if (width != ev.xconfigure.width
					|| height != ev.xconfigure.height) {
				width = ev.xconfigure.width;
				height = ev.xconfigure.height;
				printf("Size changed to: %d by %d
", width, height);
		case ButtonPress:
			return 0;

with comments and blank lines, that's 60 lines. It's essentially the same as the following HTML


in html which creates an empty page without anything on it. There are a few things to note:

The code can be found in xtut1.c

To compile and run it on a unix type system:

gcc -lX11 xtut1.c -o xtut1

Click on it to end the program

Make a copy of it and try a few things with it. Set the background white with a black border, for instance. Change the initial size of the window. Does you window manager acknowledge the changes that you make?

Comments are closed.