代码之家  ›  专栏  ›  技术社区  ›  Atmocreations

Xlib:XGetWindowAttributes总是返回1x1?

  •  3
  • Atmocreations  · 技术社区  · 14 年前

    返回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;
    }
    

    1 回复  |  直到 11 年前
        1
  •  10
  •   Doug    14 年前

    你说得对-你看到的是一扇儿童窗户。尤其是GTK应用程序,在“real”窗口下创建一个子窗口,该窗口始终为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;
    }