X Window System Examples

Ever wonder what primitive, low-level code for the X Window System looks like?

Hello, World

Sometime in the mid-1980s, I wrote a few programs that used X directly. Here’s a complete application that brings up a simple window with a greeting. It uses the system’s default widget set:

hello.c
/*
 *  This is a sample X11 program using Xt and the Athena widget set that
 *  simply puts up a main window with the text "hello" in it.
 */

#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <X11/Xaw/Label.h>

int main(int argc, char* argv[])
{
    XtAppContext app_context;
    Widget toplevel, hello;

    toplevel = XtVaAppInitialize(
        &app_context,
        "XHello",
        NULL, 0,
        &argc, argv,
        NULL,
        NULL);

    hello = XtVaCreateManagedWidget("hello", labelWidgetClass, toplevel, NULL);

    XtRealizeWidget(toplevel);
    XtAppMainLoop(app_context);
}

Command-line Arguments

Long ago there was a popular widget set called OpenLook. I had this program working back then:

showargs.c
/*
 *  This is a sample X11 program using Xt and the OpenLook widget set which
 *  simply puts up a main window displaying the command line arguments.
 */

#include <X11/Intrinsic.h>
#include <X11/StringDefs.h>
#include <Xol/OpenLook.h>
#include <Xol/StaticText.h>

int main(int argc, char* argv[])
{
    Widget toplevel;
    Arg wargs[1];
    int n;
    String message;

    toplevel = OlInitialize(argv[0], "Memo", NULL, 0, &argc, argv);

    n = 0;
    if ((message = argv[1]) != NULL) {
      XtSetArg(wargs[n], XtNstring, message);
      n++;
    }

    XtCreateManagedWidget("msg", staticTextWidgetClass, toplevel, wargs, n);
    XtRealizeWidget(toplevel);
    XtMainLoop();
}

Using Xlib

I also managed to run a program that used no tookit at all:

xlib-demo.c
/*
 *  This is a sample X11 program that uses Xlib calls only (no toolkit!).
 *  It just writes to the console the events that the window receives.
 */

#include <X11/Xlib.h>

int main(int, char*[])
{
    Display* display = XOpenDisplay(NULL);
    Window window = XCreateSimpleWindow(
        display, XDefaultRootWindow(display),
        100, 100, 200, 200, 4, 0, 0);
    XEvent event;

    XMapWindow(display, window);
    XSelectInput(display, window, KeyPressMask | ButtonPressMask | ExposureMask);

    while (True) {
      XNextEvent(display, &event);
      printf("%d\n", event.type);
    }

    return 0;
}