2010-10-11 117 views
3

我想擁有當前焦點窗口的寬度和高度。窗口的選擇就像一個魅力而高度和寬度總是返回1.Xlib:XGetWindowAttributes總是返回1x1?

#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位。

回答

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; 
} 
+0

接受:謝謝你道格。奇蹟般有效! :) 問候 – Atmocreations 2010-10-16 11:06:09