Search code examples
colorsbackgroundwindowx11xlib

Change Xlib window background color with C++


This is Linux. I have created a window and I want to change its background color to green. This is how my code looks like:

Window xwin = XCreateSimpleWindow(dis, 
                                  DefaultRootWindow(dis), 
                                  0, 0, 
                                  500, 300, 
                                  0,
                                  WhitePixel(dis, 0),
                                  WhitePixel(dis, 0));
GC gc = XCreateGC(dis, xwin, 0, NULL);
XColor color;
Colormap colormap;
char green[] = "#00FF00";

colormap = DefaultColormap(dis, 0);
XParseColor(dis, colormap, green, &color);
XAllocColor(dis, colormap, &color);

XSetBackground(dis, gc, color.pixel);

XMapWindow(dis, xwin);
XFlush(dis);

The window that I see is white. Is it possible to change window background color in Linux, using X11? Thanks!


Solution

  • If you just want a green background, the last argument of XCreateSimpleWindow is the background colour so ...

      XColor color;
      Colormap colormap;
      char green[] = "#00FF00";
    
      colormap = DefaultColormap(dis, 0);
      XParseColor(dis, colormap, green, &color);
      XAllocColor(dis, colormap, &color);
    
    
      Window xwin = XCreateSimpleWindow(dis, 
                       DefaultRootWindow(dis), 
                       0, 0, 
                       500, 300, 
                       0,
                       WhitePixel(dis, 0),
                       color.pixel);
    
    XMapWindow(dis, xwin);
    XFlush(dis);