Search code examples
c++linuxwindowcenterxlib

C++ and Xlib - center window


I have started to study GUI applications programming based on XLib directly and I am trying to create a centered window on the screen. I don't know the usual technique used to achieve this. My code (which doesn't work) is this (I use CodeBlocks)

#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>
#include <GL/glew.h>
#include <GL/freeglut.h>

int screen;
Display *display;
XSetWindowAttributes window_attributes;
Window mainwindow;
XEvent events;

int main(int argc, char** argv) {
    display = XOpenDisplay(NULL);screen = DefaultScreen(display);
    window_attributes.background_pixel = XWhitePixel(display, screen);
    window_attributes.border_pixel = XBlackPixel(display, screen);
    window_attributes.win_gravity = SouthWestGravity;

    mainwindow = XCreateWindow(display,
                             RootWindow(display, screen),
                             1, 1,
                             600, 400,
                             0,
                             CopyFromParent,
                             InputOutput,
                             CopyFromParent,
                             CWBackPixel|CWBorderPixel,
                             &window_attributes
                            );
    XMapWindow(display, mainwindow);
    XFlush(display);
    XSelectInput(display, mainwindow, ExposureMask|KeyPressMask|ButtonPressMask);
    while (1)  {
        XNextEvent(display, &events);
        switch  (events.type) {
            case Expose:
                // Lots of code that doesn't matter for my problem
            break;
        }
    }
    return 0;
}

So, I thought that window_attributes.win_gravity would do the trick but it seems like I'm doing something wrong or it must be an OS related issue.
Thanks for your help!

UPDATE
I have changed X (left position) by 100 and y (top position) by 100 but the window's position doesn't change. So, my problem is that the window's position can't be changed, no matter what it is.


Solution

    1. Gravity applies to the window's own content and children, not to its position in the parent window.
    2. Window managers can and do override top-level window position requests. Use XMoveWindow after the XMapWindow call.