Why I set xlib window background transparent faile

2019-04-11 15:00发布

问题:

I use the following code to get a transparent window, but it returns black.What's wrong with me? And, can anybody give me a simple example to create a window with transparent background?THANKS!

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

int main(int argc, char* argv[])
{
    Display* display = XOpenDisplay(NULL);

    XVisualInfo vinfo;
    XMatchVisualInfo(display, DefaultScreen(display), 32, TrueColor, &vinfo);

    XSetWindowAttributes attr;
    attr.colormap = XCreateColormap(display, DefaultRootWindow(display), vinfo.visual, AllocNone);
    attr.border_pixel = 0;
    attr.background_pixel = 0;

    Window win = XCreateWindow(display, DefaultRootWindow(display), 0, 0, 300, 200, 0, vinfo.depth, InputOutput, vinfo.visual, CWColormap | CWBorderPixel | CWBackPixel, &attr);
    XSelectInput(display, win, StructureNotifyMask);
    GC gc = XCreateGC(display, win, 0, 0);

    Atom wm_delete_window = XInternAtom(display, "WM_DELETE_WINDOW", 0);
    XSetWMProtocols(display, win, &wm_delete_window, 1);

    XMapWindow(display, win);

    int keep_running = 1;
    XEvent event;

    while (keep_running) {
        XNextEvent(display, &event);

        switch(event.type) {
            case ClientMessage:
                if (event.xclient.message_type == XInternAtom(display, "WM_PROTOCOLS", 1) && (Atom)event.xclient.data.l[0] == XInternAtom(display, "WM_DELETE_WINDOW", 1))
                    keep_running = 0;

                break;

            default:
                break;
        }
    }

    XDestroyWindow(display, win);
    XCloseDisplay(display);
    return 0;
}

回答1:

Your code works fine for me:

kde:

openbox + xcompmgr:

Most likely you are not running composite manager. Try to start xcompmgr command

Also check _NET_WM_CM_S0 selection owner - it should point to a window created by composite manager.

#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <stdio.h>

int main(int argc, char* argv[])
{
    Display* display = XOpenDisplay(NULL);

    Atom cmAtom = XInternAtom(display, "_NET_WM_CM_S0", 0);
    Window cmOwner = XGetSelectionOwner(display, cmAtom);

    printf("Composite manager window: %i\n", cmOwner);

    XCloseDisplay(display);
    return 0;
}

Update:

Try to set override-redirect to prevent WM decorations from obscuring your window.

attr.border_pixel = 0;
attr.background_pixel = 0;
attr.override_redirect = 1; /* this line added */

Window win = XCreateWindow(display, DefaultRootWindow(display), 0, 0, 300, 200, 0, 
vinfo.depth, InputOutput, vinfo.visual, 
CWColormap | CWBorderPixel | CWBackPixel | CWOverrideRedirect /* and this one*/, &attr);