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-04

骨組みのコード

xdemo.c
#include <X11/Xlib.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
    Display *dpy = XOpenDisplay(NULL);         // Xサーバへ接続
    if (!dpy) {
        fprintf(stderr, "Can't open display\n");
        exit(1);
    }

    int screen = DefaultScreen(dpy);           // 使用するスクリーン番号
    Window win = XCreateSimpleWindow(
        dpy,                     // Xサーバとの接続ハンドル
        RootWindow(dpy, screen),// 親ウィンドウに RootWindow (最上位のウィンドウ) を指定
        100, 100, 400, 200,                    // x, y, width, height
        1,                                     // 境界線の太さ
        BlackPixel(dpy, screen),               // 境界線の色
        WhitePixel(dpy, screen)                // 背景色
    );

    XSelectInput(dpy, win, ExposureMask | KeyPressMask); // 描画とキー入力イベントを監視
    XMapWindow(dpy, win);                      // ウィンドウを画面に表示

    XEvent event;
    while (1) {
        XNextEvent(dpy, &event);               // イベント待ち

        if (event.type == Expose) {            // 再描画要求
            XDrawString(dpy, win,
                        DefaultGC(dpy, screen),
                        50, 100, "Hello Xlib!", 11);
        }
        else if (event.type == KeyPress) {     // キーが押されたら終了
            break;
        }
    }

    XCloseDisplay(dpy);                        // 接続終了
    return 0;
}

構成要素 説明
XOpenDisplay() Xサーバと接続を行う関数。ディスプレイ名を指定して、Xサーバへ接続する。
XCreateSimpleWindow() ウィンドウを作成する関数。指定した親ウィンドウ上に新しいウィンドウを作成。
XMapWindow() 作成したウィンドウを画面に表示する関数。ウィンドウは最初非表示なので、表示する必要がある。
XSelectInput() 受け取るイベント(ExposeKeyPressなど)を指定する関数。どのイベントを待機するかを設定。
XNextEvent() イベントが発生するまでプログラムを止めて待機。
XDrawString() ウィンドウ上の指定した座標に文字列を描画する関数。

動作確認

gcc -o xdemo xdemo.c -lX11
./xdemo

image.png

動作環境

gcc version 11.4.0 (Ubuntu 11.4.0-1ubuntu1~22.04)
image.png

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?