2013年1月7日 星期一

Xlib 基本視窗程式

以下程式碼使用 Xlib 建立一個背景為黑色、大小為 512x512 的視窗。
#include <string.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>

#define TITLE_STRING "Xlib test"

int main(int argc, char **argv)
{
	int quit = False;
	Display* display = NULL;
	Window window;
	XTextProperty  title;
	XEvent event;
	Atom wm_delete_window;

	display = XOpenDisplay(NULL);
	window = XCreateWindow(display, RootWindow(display, 0), 0, 0, 512, 512, 0,  CopyFromParent, CopyFromParent,  CopyFromParent, 0, NULL);

	XSetWindowBackground(display, window, BlackPixel(display, 0));

	title.value = (unsigned char*)TITLE_STRING;
	title.encoding = XA_STRING;
	title.format = 8;
	title.nitems = strlen(TITLE_STRING);

	XSetWMProperties(display, window, &title, &title, NULL, 0, NULL, NULL, NULL);

	wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", False);
	XSetWMProtocols(display, window, &wm_delete_window, 1);

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

	while(!quit)
	{
		XNextEvent(display, &event);

		switch(event.type)
		{
		case ClientMessage:
			if(event.xclient.data.l[0] == wm_delete_window)
			{
				XDestroyWindow(display, window);
				quit = True;
			}
			break;
		}
	}

	XCloseDisplay(display);
	return 0;
}