6

現在フォーカスされているウィンドウの幅と高さが欲しいです。ウィンドウの選択は魅力のように機能しますが、高さと幅は常に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 ビットを使用しています。

4

1 に答える 1

14

その通りです。子ウィンドウが表示されています。特に GTK アプリケーションは、「実際の」ウィンドウの下に子ウィンドウを作成します。これは常に 1x1 であり、アプリケーションにフォーカスがある場合は常にフォーカスを取得します。GNOME ターミナルを使用してプログラムを実行しているだけの場合は、フォーカス (ターミナル) を持つ GTK アプリケーションが常に表示されます。

GTK 以外のプログラムにたまたまフォーカスがあるような方法でプログラムを実行すると、これは起こりませんが、トップレベル ウィンドウではなく、フォーカスのある子ウィンドウを見つけてしまう可能性があります。(これを行う 1 つの方法は、次の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;
}
于 2010-10-14T10:05:37.973 に答える