【问题标题】:C++ and Xlib - center windowC++ 和 Xlib - 中心窗口
【发布时间】:2012-09-10 00:58:43
【问题描述】:

我已经开始直接研究基于 XLib 的 GUI 应用程序编程,我正在尝试在屏幕上创建一个居中的窗口。我不知道用来实现这一点的常用技术。我的代码(不起作用)是这样的(我使用 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;
}

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

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

【问题讨论】:

  • 我不知道这是否是实现它的最佳方式,但是您不能使用 XWidthOfScreen/XHeightOfScreen 找出窗口的正确位置吗?
  • 出了点问题,窗口位置不会改变顶部和左侧的值。
  • 尝试 XMoveWindow 明确窗口的位置。 IIRC 给 XCreateWindow 的位置只是一个提示。
  • @ali:请注意,这样做会覆盖窗口管理器的决定,并且可能会覆盖窗口管理器的用户配置。

标签: c++ linux window center xlib


【解决方案1】:
  1. 重力适用于窗口自身的内容和子窗口,而不适用于其在父窗口中的位置。
  2. 窗口管理器可以并且确实会覆盖顶级窗口位置请求。在XMapWindow 调用之后使用XMoveWindow

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2012-02-10
      • 2015-07-21
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多