【问题标题】:Xlib: XGetWindowAttributes always returns 1x1?Xlib:XGetWindowAttributes 总是返回 1x1?
【发布时间】:2010-10-11 20:30:41
【问题描述】:

我想知道当前焦点窗口的宽度和高度。窗口的选择就像一个魅力,而高度和宽度总是返回 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 位。

【问题讨论】:

    标签: c++ c xlib xorg


    【解决方案1】:

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

    如果您以非 GTK 程序恰好具有焦点的方式运行程序,则不会发生这种情况,但您最终仍可能会找到具有焦点的子窗口而不是顶层窗户。 (这样做的一种方法是在你的程序之前运行sleep,如下所示:sleep 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;
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多