C++ and Xlib - center window

懵懂的女人 提交于 2019-12-08 06:32:28

问题


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.


回答1:


  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.



回答2:


In your function where you create window you should calculate the starting x,y coordinates of your window in the screen:

XDisplayWidth(dpy, sreen); XDisplayHeight(dpy, sreen);

After that you should make your calculation (like .../2 + win.size.x ....) to center your window.



来源:https://stackoverflow.com/questions/12465552/c-and-xlib-center-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!