Window creation/X11

From Rosetta Code
Revision as of 20:55, 13 November 2008 by rosettacode>Blue Prawn (initial version with C and OCaml)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Window creation/X11
You are encouraged to solve this task according to the task description, using any language you may know.

Create a simple Xlib application that draws a box and "Hello World" in a window.

C

<C>#include <X11/Xlib.h>

  1. include <stdio.h>
  2. include <stdlib.h>
  3. include <string.h>

int main(void) {

  Display *d;
  Window w;
  XEvent e;
  char *msg = "Hello, World!";
  int s;
  d = XOpenDisplay(NULL);
  if (d == NULL) {
     fprintf(stderr, "Cannot open display\n");
     exit(1);
  }
  s = DefaultScreen(d);
  w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 100, 100, 1,
                          BlackPixel(d, s), WhitePixel(d, s));
  XSelectInput(d, w, ExposureMask | KeyPressMask);
  XMapWindow(d, w);
  while (1) {
     XNextEvent(d, &e);
     if (e.type == Expose) {
        XFillRectangle(d, w, DefaultGC(d, s), 20, 20, 10, 10);
        XDrawString(d, w, DefaultGC(d, s), 10, 50, msg, strlen(msg));
     }
     if (e.type == KeyPress)
        break;
  }
  XCloseDisplay(d);
  return 0;

} </C>


OCaml

Library: OCaml-Xlib

<ocaml>#directory "+Xlib"

  1. load "Xlib.cma"

open Xlib

let () =

 let msg = "Hello, World!" in
 let d = xOpenDisplay "" in
 let s = xDefaultScreen d in
 let w = xCreateSimpleWindow d (xRootWindow d s) 10 10 100 100 1
                               (xBlackPixel d s) (xWhitePixel d s) in
 xSelectInput d w [ExposureMask; KeyPressMask];
 xMapWindow d w;
 let e = new_xEvent() in
 try while true do
   xNextEvent d e;
   match xEventType e with
   | Expose ->
       xFillRectangle d w (xDefaultGC d s) 20 20 10 10;
       xDrawString d w (xDefaultGC d s) 10 50 msg;
   | KeyPress ->
       raise Exit
   | _ -> ()
 done
 with Exit ->
   xCloseDisplay d;
</ocaml>