リアルタイムなマウス状態の取得

概要

現在のマウス状態をイベントを使わずに取得する。

XQueryKeymap()関数と同様にして、マウスの現在の位置や ボタンの状態はXQueryPointer()関数により取得できる。

ソース

xqpointer.cpp
#include <gtkmm.h>
#include <gdk/gdkx.h>
#include <iostream>

void show_pointer( Glib::RefPtr<Gdk::Window> win )
{
    int x_r, y_r;
    int x_w, y_w;
    Window root;
    Window child;
    unsigned int buttons;
    XQueryPointer( GDK_WINDOW_XDISPLAY( Glib::unwrap( win ) ),
                   GDK_WINDOW_XWINDOW( Glib::unwrap( win ) ),
                   &root, &child,
                   &x_r, &y_r, &x_w, &y_w, &buttons );

    std::cout << "x_r = " << x_r << " y_r= " << y_r
              << "x_w = " << x_w << " y_w= " << y_w
              << " button = " << buttons; 

    if( buttons & Button1Mask ) std::cout << " b1";
    if( buttons & Button2Mask ) std::cout << " b2";
    if( buttons & Button3Mask ) std::cout << " b3";
    if( buttons & ShiftMask ) std::cout << " shift";
    if( buttons & ControlMask ) std::cout << " ctrl";

    std::cout << std::endl;
}


class MainWin : public Gtk::Window
{
public:
    MainWin(){ add_events( Gdk::BUTTON_PRESS_MASK ); }

protected:
    virtual bool on_button_press_event( GdkEventButton* ev ){ show_pointer( get_window() ); }
};

int main( int argc, char *argv[] )
{
    Gtk::Main kit( argc, argv );
    MainWin mainwin;
    Gtk::Main::run( mainwin );

    return 0;
}

コンパイル

必要なコンパイルオプションは pkg-config を使って取得する。

g++ xqpointer.cpp -o xqpointer `pkg-config gtkmm-2.4 --cflags --libs`

結果

ウィンドウをクリックすると現在の座標やボタン状態が表示される。