Language: C
GUI / Windowing
Xlib was developed in the mid-1980s as the primary client library for X11. It provides a low-level interface to X server operations, allowing developers to build graphical applications directly. Although higher-level toolkits like GTK and Qt are more commonly used today, Xlib is still valuable for lightweight, custom, or embedded X11 applications.
Xlib is the standard C library for interfacing with the X Window System (X11) on Unix-like operating systems. It allows applications to create and manage windows, handle user input events, draw graphics, and communicate with the X server.
sudo apt install libx11-devInstall XQuartz to get X11 headers and librariesXlib is mainly for Unix-like systems; use Cygwin/X or similar for WindowsXlib enables C programs to open a connection to the X server, create windows, manage events like keyboard and mouse inputs, and draw graphics primitives such as lines, rectangles, and text.
#include <X11/Xlib.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
Display *d;
Window w;
XEvent e;
int s;
d = XOpenDisplay(NULL);
if (d == NULL) {
fprintf(stderr, "Cannot open display\n");
exit(1);
}
s = DefaultScreen(d);
w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 200, 200, 1,
BlackPixel(d, s), WhitePixel(d, s));
XSelectInput(d, w, ExposureMask | KeyPressMask);
XMapWindow(d, w);
while (1) {
XNextEvent(d, &e);
if (e.type == Expose) {
XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10);
}
if (e.type == KeyPress)
break;
}
XCloseDisplay(d);
return 0;
}Opens a connection to the X server, creates a window, listens for expose and keypress events, draws a rectangle, and closes the display.
#include <X11/Xlib.h>
// Use functions like XDrawLine, XDrawRectangle, XDrawArc to draw shapes on a windowDemonstrates low-level drawing operations using Xlib functions to create lines, rectangles, circles, and arcs.
// Use XSelectInput to listen for multiple event types such as KeyPressMask, ButtonPressMask, ExposureMask
// Use XNextEvent to process events in an event loopAllows handling of keyboard, mouse, and window events in a single loop efficiently.
// Use XLoadFont and XDrawString to draw text on windows with XlibEnables rendering text with specific fonts and coordinates in a window.
Always check the return values of Xlib functions to catch errors early.
Use event masks efficiently to avoid unnecessary event handling overhead.
Close the Display connection using XCloseDisplay to release resources.
Consider using higher-level toolkits like GTK or Qt for complex GUI applications.
Separate event handling and drawing logic for maintainability.