本文主要介绍了X Window研究笔记的一个简单示例。
22.X Window 简单示例
对大多数linux程序员来说,很少有机会直接用Xlib去开发应用程序,那样开发效率太低,一般都是使用基于像GTK+和QT这样的toolkit。不过了解一下
XWindow编程没有什么坏处,这里举一个简单的例子,供新手参考:
xdemo.c
#include <string.h>
#include <X11/Xlib.h>
#include <X11/keysym.h>
int main(int argc, char* argv[])
...{
Display* display = XOpenDisplay(NULL);
int screen = DefaultScreen(display);
int width = DisplayWidth(display, screen)/2;
int height = DisplayHeight(display, screen)/2;
Window win = XCreateSimpleWindow(display, RootWindow(display, screen),
0, 0, width, height, 3, BlackPixel(display, screen), WhitePixel(display, screen));
XSelectInput(display, win, ExposureMask|KeyPressMask | ButtonPressMask | StructureNotifyMask);
GC gc = XCreateGC(display, win, 0, NULL);
XMapWindow(display, win);
while(1)
...{
XEvent event = ...{0};
XNextEvent(display, &event);
switch(event.type)
...{
case ConfigureNotify:
...{
width = event.xconfigure.width;
height = event.xconfigure.height;
break;
}
case Expose:
...{
XSetForeground(display, gc, WhitePixel(display, screen));
XFillRectangle(display, win, gc, 0, 0, width, height);
XSetForeground(display, gc, BlackPixel(display, screen));
XDrawString(display, win, gc, width/2, height/2, "XWindow", 7);
break;
}
case KeyPress:
...{
if(event.xkey.keycode == XKeysymToKeycode(display, XK_Escape))
...{
XFreeGC(display, gc);
XCloseDisplay(display);
return 0;
}
}
default:break;
}
}
return 0;
}
Makefile
all:
gcc -g -lX11 xdemo.c -o xdemo
clean:
rm -f xdemo
查看本文来源