首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

XCB 程式設計教學(一):快速入門建立第一個 X 視窗

     編輯:關於C++

為何學習 XCB?

XCB 是 X 協定的 C 語言綁定,最接近底層的 UI 函式庫。現代應用多用 Qt/GTK 等高層封裝,但學習 XCB 能深入理解 X 協定、視窗系統架構、事件模型等核心原理。

最簡視窗程式


#include <stdlib.h> #include <sys/time.h> #include <unistd.h>
#include <xcb/xcb.h> #include <stdio.h>

double get_time() {
    struct timeval tv; gettimeofday(&tv, NULL);
    return tv.tv_sec + tv.tv_usec / 1000000.0;
}

int main() {
    double start = get_time();
    xcb_connection_t *conn = xcb_connect(NULL, NULL);
    const xcb_setup_t *setup = xcb_get_setup(conn);
    xcb_screen_iterator_t iter = xcb_setup_roots_iterator(setup);
    xcb_screen_t *screen = iter.data;

    xcb_window_t win = xcb_generate_id(conn);
    xcb_create_window(conn, XCB_COPY_FROM_PARENT, win, screen->root,
                      100, 100, 400, 300, 10,
                      XCB_WINDOW_CLASS_INPUT_OUTPUT, screen->root_visual, 0, NULL);
    xcb_map_window(conn, win); xcb_flush(conn);

    printf("耗時:%f 秒。\n", get_time() - start); fflush(stdout);
    pause(); // 無事件迴圈,需 Ctrl+C 結束
    xcb_disconnect(conn); return 0;
}

建立視窗四步驟

  1. 連線 X Server:xcb_connect() 回傳 xcb_connection_t*,可取得螢幕編號。
  2. 取得 Setup 資訊:xcb_get_setup() 含協定版本、位元序等,通常不需直接操作。
  3. 取得 Screen 物件:xcb_setup_roots_iterator() 回傳迭代器,單螢幕取 iter.data。xcb_screen_t 含根視窗、尺寸、色深、黑白像素值等關鍵資訊。
  4. 建立並顯示視窗:
    1. xcb_generate_id() 產生視窗 ID
    2. xcb_create_window() 建立視窗(需 parent、幾何、類別、visual 等)
    3. xcb_map_window() 映射顯示
    4. xcb_flush() 送出請求

執行畫面

視窗無背景,顯示桌面殘影(未處理 EXPOSE 事件)。

進階:列舉所有 Screen


int screen_num;
xcb_connection_t *conn = xcb_connect(NULL, &screen_num);
xcb_screen_iterator_t iter = xcb_setup_roots_iterator(xcb_get_setup(conn));
printf("Current screen number: %d\niter.rem = %d\n", screen_num, iter.rem);
for (; iter.rem; xcb_screen_next(&iter)) {
    xcb_screen_t *sc = iter.data;
    printf("root=%u depth=%u white=%u black=%u %ux%u px %ux%u mm\n",
           sc->root, sc->root_depth, sc->white_pixel, sc->black_pixel,
           sc->width_in_pixels, sc->height_in_pixels,
           sc->width_in_millimeters, sc->height_in_millimeters);
}

執行結果

資料結構探索技巧

Vim + ctags + taglist.vim:游標停留在型別/函式上按 Ctrl+] 即跳轉定義。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved