Xlib:XGetWindowAttributes总是返回1x1?

时间:2010-10-11 20:30:41

标签: c++ c xlib xorg

我想拥有当前焦点窗口的宽度和高度。窗口的选择就像一个魅力,而高度和宽度总是返回1。

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

int main(int argc, char *argv[])
{
    Display *display;
    Window focus;
    XWindowAttributes attr;
    int revert;

    display = XOpenDisplay(NULL);
    XGetInputFocus(display, &focus, &revert);
    XGetWindowAttributes(display, focus, &attr);
    printf("[0x%x] %d x %d\n", (unsigned)focus, attr.width, attr.height);

    return 0;
}

这不是“真正的”窗口,而是当前活动的组件(如文本框或按钮吗?)为什么它的大小为1x1呢?如果是这种情况,我如何让应用程序的主窗口包含此控件?意味着...有点顶级窗口,除了根窗口之外的最顶层窗口。

PS:不知道这是否真的很重要;我使用Ubuntu 10.04 32和64位。

1 个答案:

答案 0 :(得分:9)

你是对的 - 你正在看一个儿童窗户。特别是GTK应用程序在“真实”窗口下创建一个子窗口,该窗口始终为1x1,并且在应用程序具有焦点时始终获得焦点。如果您只是使用GNOME终端运行程序,那么您将始终看到具有焦点的GTK应用程序(终端)。

如果以非GTK程序碰巧有焦点的方式运行你的程序,那么这不会发生,但你仍然可能最终找到一个焦点而不是顶级的子窗口窗口。 (这样做的一种方法是在你的程序之前运行sleepsleep 4; ./my_program - 这让你有机会改变焦点。)

要查找顶级窗口,我认为XQueryTree会有所帮助 - 它会返回父窗口。

这对我有用:

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

/*
Returns the parent window of "window" (i.e. the ancestor of window
that is a direct child of the root, or window itself if it is a direct child).
If window is the root window, returns window.
*/
Window get_toplevel_parent(Display * display, Window window)
{
     Window parent;
     Window root;
     Window * children;
     unsigned int num_children;

     while (1) {
         if (0 == XQueryTree(display, window, &root,
                   &parent, &children, &num_children)) {
             fprintf(stderr, "XQueryTree error\n");
             abort(); //change to whatever error handling you prefer
         }
         if (children) { //must test for null
             XFree(children);
         }
         if (window == root || parent == root) {
             return window;
         }
         else {
             window = parent;
         }
     }
}

int main(int argc, char *argv[])
{
    Display *display;
    Window focus, toplevel_parent_of_focus;
    XWindowAttributes attr;
    int revert;

    display = XOpenDisplay(NULL);
    XGetInputFocus(display, &focus, &revert);
    toplevel_parent_of_focus = get_toplevel_parent(display, focus);
    XGetWindowAttributes(display, toplevel_parent_of_focus, &attr);
    printf("[0x%x] %d x %d\n", (unsigned)toplevel_parent_of_focus, 
       attr.width, attr.height);

    return 0;
}