To draw text in a window using the X11 library in C, you can use the XDrawString or XDrawText functions provided by the library. For this, you'll use Xlib functions to create a window, obtain a graphics context, and then draw the text into that context.
Here's a simple example that demonstrates how to create a window and draw text inside it using Xlib:
#include <X11/Xlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
Display *display;
Window window;
XEvent event;
int screen;
GC gc; // Graphics Context
char *text = "Hello, X11!";
int text_len = strlen(text);
/* Open connection to the X server */
display = XOpenDisplay(NULL);
if (display == NULL) {
fprintf(stderr, "Cannot open display\n");
exit(1);
}
screen = DefaultScreen(display);
/* Create window */
window = XCreateSimpleWindow(display, RootWindow(display, screen), 10, 10, 200, 100, 1,
BlackPixel(display, screen), WhitePixel(display, screen));
XSelectInput(display, window, ExposureMask | KeyPressMask);
XMapWindow(display, window);
/* Create Graphics Context */
gc = XCreateGC(display, window, 0, NULL);
XSetForeground(display, gc, BlackPixel(display, screen));
XSetBackground(display, gc, WhitePixel(display, screen));
/* Load a font */
XFontStruct *fontinfo = XLoadQueryFont(display, "fixed");
if (!fontinfo) {
fprintf(stderr, "Unable to load fixed font\n");
exit(1);
}
XSetFont(display, gc, fontinfo->fid);
/* Event loop */
while (1) {
XNextEvent(display, &event);
if (event.type == Expose) {
XDrawString(display, window, gc, 50, 50, text, text_len);
} else if (event.type == KeyPress) {
break; // Exit on any key press
}
}
/* Clean up */
XUnloadFont(display, fontinfo->fid);
XFreeGC(display, gc);
XDestroyWindow(display, window);
XCloseDisplay(display);
return 0;
}
This program follows these steps:
- Open a connection to the X server.
- Create a simple window.
- Create a Graphics Context (GC).
- Query and load a fixed font to use with the text.
- Draw the string
"Hello, X11!" into the window when the window is exposed (when parts of the window need to be redrawn, such as after being covered by another window).
- Exit the main loop and clean up resources if a key press event is detected.
You will need the development version of the X11 libraries (often libx11-dev or similar package) installed on your system to compile this. You can compile the program with the following command:
gcc -o hello_x11 hello_x11.c -lX11
Please note that this is just a basic introduction to drawing text in an X11 window. Xlib provides many other features and functions for performing more advanced operations, such as drawing graphics, handling more complex events, and so on.