Xlib - Example

Example

The following program 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 #include #include #include int main { Display *display; Window window; XEvent event; char *msg = "Hello, World!"; int s; /* open connection with the server */ display = XOpenDisplay(NULL); if (display == NULL) { fprintf(stderr, "Cannot open display\n"); exit(1); } s = DefaultScreen(display); /* create window */ window = XCreateSimpleWindow(display, RootWindow(display, s), 10, 10, 200, 200, 1, BlackPixel(display, s), WhitePixel(display, s)); /* select kind of events we are interested in */ XSelectInput(display, window, ExposureMask | KeyPressMask); /* map (show) the window */ XMapWindow(display, window); /* event loop */ while (1) { XNextEvent(display, &event); /* draw or redraw the window */ if (event.type == Expose) { XFillRectangle(display, window, DefaultGC(display, s), 20, 20, 10, 10); XDrawString(display, window, DefaultGC(display, s), 50, 50, msg, strlen(msg)); } /* exit on key press */ if (event.type == KeyPress) break; } /* close connection to server */ XCloseDisplay(display); return 0; }

The client creates a connection with the server by calling XOpenDisplay. It then requests the creation of a window with XCreateSimpleWindow. A separate call to XMapWindow is necessary for mapping the window, that is, for making it visible on the screen.

The square is drawn by calling XFillRectangle. This operation can only be performed after the window is created. However, performing it once may not be enough. Indeed, the content of the window is not always guaranteed to be preserved. For example, if the window is covered and then uncovered again, its content might require being redrawn. The program is informed that the window or a part of it has to be drawn by the reception of an Expose event.

The drawing of the window content is therefore made inside the loop handling the events. Before entering this loop, the events the application is interested in are selected, in this case with XSelectInput. The event loop waits for an incoming event: if this event is a key press, the application exits; if it is an expose event, the window content is drawn. The function XNextEvent blocks and flushes the request buffer if there is no event in the queue.

Read more about this topic:  Xlib

Famous quotes containing the word example:

    Our intellect is not the most subtle, the most powerful, the most appropriate, instrument for revealing the truth. It is life that, little by little, example by example, permits us to see that what is most important to our heart, or to our mind, is learned not by reasoning but through other agencies. Then it is that the intellect, observing their superiority, abdicates its control to them upon reasoned grounds and agrees to become their collaborator and lackey.
    Marcel Proust (1871–1922)