1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LINUX GUI マウス座標を取得(備忘録)

Last updated at Posted at 2025-05-05

GUIの骨組み

昨日書いた備忘録
https://qiita.com/earthen94/items/8402809a401d904120ef

マウス座標を取得するプログラム

mousepos.c
#include <X11/Xlib.h>
#include <stdio.h>

int main() {
    Display *dpy;
    Window root, win;
    XEvent event;
    int screen;

    dpy = XOpenDisplay(NULL);
    if (dpy == NULL) {
        fprintf(stderr, "Xサーバに接続できません\n");
        return 1;
    }

    screen = DefaultScreen(dpy);
    root = RootWindow(dpy, screen);

    // 300x200のウィンドウを作成
    win = XCreateSimpleWindow(dpy, root, 100, 100, 300, 200, 1,
                              BlackPixel(dpy, screen), WhitePixel(dpy, screen));

    // 入力イベントとして「ポインタ移動(マウス移動)」を選択
    XSelectInput(dpy, win, ExposureMask | PointerMotionMask);

    XMapWindow(dpy, win);

    while (1) {
        XNextEvent(dpy, &event);

        if (event.type == MotionNotify) {
            printf("マウス座標: (%d, %d)\n", event.xmotion.x, event.xmotion.y);
        }
    }

    XCloseDisplay(dpy);
    return 0;
}

動作確認

マウスの矢印が画面の中に入ると、端末上に座標を表示する

gcc -o mousepos mousepos.c -lX11
./mousepos

image.png

座標取得に関わる部分

  // 入力イベントとして「ポインタ移動(マウス移動)」を選択
    XSelectInput(dpy, win, ExposureMask | PointerMotionMask);
       XNextEvent(dpy, &event);

        if (event.type == MotionNotify) {
            printf("マウス座標: (%d, %d)\n", event.xmotion.x, event.xmotion.y);
        }

動作環境

image.png

余談

連休で4月29日から日本に帰省しており、実家の古いパソコンで色々実験が出来ました。
今日名古屋へ移動して明日上海に戻ります。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?