[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Tcl/Tk Up: Examples Previous: Vogle

Xlib

The X Window System is a portable, network-transparent window system originally developed at MIT who still maintain it under the auspices of the X Consortium, a group whose membership includes most of the major computer firms. It's free too. See the handout for details

/* A SAMPLE X11 PROGRAM WRITTEN IN C */
/* compile using c89 -I/usr/include/X11R5 -L/usr/lib/X11R5 
 * -o demo demo.c -lX11 */
/* It draws a red line then some text */
#include <stdio.h>
#include <X11/Xlib.h>
     Display *display;
     Window  window;
     XSetWindowAttributes attributes;
     XGCValues gr_values;
     XFontStruct *fontinfo;
     GC gr_context;
     Visual *visual;
     int depth;
     XKeyEvent event;
     XColor    color, dummy;

main (argc, argv)
char   *argv[];
int     argc;
{
     display = XOpenDisplay(NULL);
     visual = DefaultVisual(display,0);
     depth  = DefaultDepth(display,0);
     attributes.background_pixel      = XWhitePixel(display,0);

     /* create a window */
     window=     XCreateWindow( display,XRootWindow(display,0),
                                200,200, 350,200, 5, depth,  
                                InputOutput,visual ,CWBackPixel, 
                                &attributes);
     XSelectInput(display,window,ExposureMask|KeyPressMask) ;
     /* pick your font */
     fontinfo = XLoadQueryFont(display,"6x10");
     /* pick your color */
     XAllocNamedColor(display, DefaultColormap(display, 0),"red",
                      &color,&dummy);

     gr_values.font =   fontinfo->fid;
     gr_values.foreground = color.pixel;
     gr_context=XCreateGC(display,window,GCFont+GCForeground, &gr_values);
     XMapWindow(display,window);
     /* wait for a key press */
     while(1){
        XNextEvent(display,&event);
        switch(event.type){
        case Expose:
            /* Now draw a line ... */
            XDrawLine(display,window,gr_context,0,0,100,100);
            /* ...and some text    */
            XDrawString(display,window,gr_context,100,100,"hello",5);
            continue;
        default: 
            break;
        }
     }
   }







Tim Love
2001-07-26