#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>
#include <stdio.h>
int main(int argc,char *argv[])
{
static char *string="Hello world!";
Display *display;
int screen_num;
Window win;
unsigned int width,height;
unsigned int border_width=4;
unsigned int display_width,display_height;
int count;
XEvent report;
GC gc;
unsigned long valuemask=0;
XGCValues values;
char *display_name=NULL;
//和X服务器连接
if((display=XOpenDisplay(display_name))==NULL)
{
printf("Cannot connect to X server %s\n",XDisplayName(display_name));
return -1;
}
//获得缺省的screen_num
screen_num=DefaultScreen(display);
//获得屏幕的宽度和高度
display_width=DisplayWidth(display,screen_num);
display_height=DisplayHeight(display,screen_num);
//指定所建立窗口的宽度和高度
width=display_width/3;
height=display_height/4;
//建立窗口
win=XCreateSimpleWindow(display,
RootWindow(display,screen_num),
0,0,width,height,
border_width,
BlackPixel(display,screen_num),
WhitePixel(display,screen_num));
//选择窗口感兴趣的事件掩码
XSelectInput(display,win,ExposureMask|KeyPressMask|
ButtonPressMask|StructureNotifyMask
) ;
//建立GC
gc=XCreateGC(display,win,valuemask,&values);
//显示窗口
XMapWindow(display,win) ;
//进入事件循环
while(1)
{
//取得队列中的事件
XNextEvent(display,&report) ;
switch(report.type){
case Expose:
//取得最后一个曝光事件
if(report.xexpose.count!=0)break;
//写字符串
XDrawString(display,win,gc,width/2,height/2,string,strlen(string));
break;
case ConfigureNotify:
width=report.xconfigure.width;
height=report.xconfigure.height;
break;
case ButtonPress:
case KeyPress:
XFreeGC(display,gc);
XCloseDisplay(display);
return 1;
default:
break;
}
}
}
使用编译命令 :gcc -o ex1 ex1.c -lX11
运行程序:./ex1