Xlib programming basics

From Wikiversity
Jump to navigation Jump to search

Xlib is an application programming interface (API) for X Window. A program that uses Xlib consists of 4 basic tasks:

  • Open a connection to a X Window server.
  • Create windows for the user interface and map them so they are shown to the user
  • Respond to events received from the X Window server. Drawing the user interface is included in this step.
  • Close a connection to a X Window server in response to a user's action when the time is right. Like for example when clicking quit from a menu.

Open A Connection[edit | edit source]

#include <X11/Xlib.h>

int main(int argc, char **argv) {
  Display *d = XOpenDisplay(argc > 1 ? argv[1] : NULL);
  return 0;
}

XOpenDisplay is a function that opens a connection to a X Window server. XOpenDisplay gets passed a string (e.g char*) that lets you control what display to connect to. You can also tell Xlib to attempt a connection with the default display by passing NULL instead. If a connection to a X Window server is successful, XOpenDisplay returns an allocated pointer to a Display structure, otherwise a null pointer (e.g (Display*)NULL) is returned.

You should check whether the connection was successful or not before calling any other functions from Xlib. Most other Xlib functions depend on knowing which display is being used. You may also need to know which display is being used in order to get characteristics of the display, such as how many screens there are, what resolutions does each screen support, and what color depths does each screen resolution support. A typical PC only has one screen, but supports several different screen resolutions and color depths for example.

Close A Connection[edit | edit source]

#include <X11/Xlib.h>

int main(int argc, char **argv) {
  Display *d = XOpenDisplay(argc > 1 ? argv[1] : NULL);
  if (!d) {
    return -1;
  }
  int err = XCloseDisplay(d);
  return err;
}