The X Window System

Introduction

Introductory Examples

Writing "Hello, World" in a window

/*****************************************************************************
*
*  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);
}

A program that writes command line arguments in a window

/*****************************************************************************
*
*  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, msg_widget;
  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++;
  }

  msg_widget = XtCreateManagedWidget(
    "msg", staticTextWidgetClass, toplevel, wargs, n);

  XtRealizeWidget(toplevel);
  XtMainLoop();
}

A program that does not use a toolkit

/*****************************************************************************
*
*  xlib-demo.c
*
*  This is a sample  X11 program which 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;
}

For More Info