C++和Xlib - 中心窗口

C++ and Xlib - center window

本文关键字:心窗 窗口 Xlib C++      更新时间:2023-10-16

我已经开始直接研究基于 XLib 的 GUI 应用程序编程,我正在尝试在屏幕上创建一个居中窗口。我不知道用于实现这一目标的常用技术。我的代码(不起作用)是这个(我使用代码块)

#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;
}

所以,我认为window_attributes.win_gravity可以解决问题,但似乎我做错了什么,或者一定是与操作系统相关的问题。
感谢您的帮助!

更新
我将 X(左侧位置)更改了 100,将 y(顶部位置)更改了 100,但窗口的位置没有改变。所以,我的问题是窗口的位置不能改变,不管它是什么。

  1. 重力适用于窗口自己的内容和子窗口,而不是其在父窗口中的位置。
  2. 窗口
  3. 管理器可以并且确实覆盖顶级窗口位置请求。在XMapWindow呼叫使用XMoveWindow

在创建窗口的函数中,您应该计算屏幕中窗口的起始 x,y 坐标:

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

之后,您应该进行计算(例如.../2 + win.size.x ...)以使窗口居中。