You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu下C++调用XGetImage()始终返回BadMatch错误求助

问题描述

我正在为Ubuntu编写一个C++程序,用于获取鼠标悬停位置像素的RGB值。使用XGetImage()函数时始终返回BadMatch错误。

初始代码

#include <iostream>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xresource.h>


int main(int, char**) {
    XColor c;
    Display *display = XOpenDisplay((char *) NULL);
    Window root = XRootWindow(display, XDefaultScreen(display));
    XWindowAttributes attr;
    XGetWindowAttributes(display, root, &attr);
    XMapRaised(display, root);
    unsigned int width = attr.width;
    unsigned int height = attr.height;
    root = attr.root;
    /*
    XQueryPointer(display, win, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask_return);
    std::printf("root_x: %d\troot_y: %d\nchild_x: %d\tchild_y: %d\n",
        root_x,
        root_y,
        win_x,
        win_y
    );*/
    XMapRaised(display, root);
    XImage *image = XGetImage(display, root, 0, 0, 100, 100, AllPlanes, ZPixmap);
    c.pixel = XGetPixel(image, 0, 0);
    std::cout << c.red << std::endl;
    XFree(image);
    XQueryColor(display, XDefaultColormap(display, XDefaultScreen(display)), &c);
    std::cout << c.red << " " << c.green << " " << c.blue << std::endl;
    XCloseDisplay(display);
    return 0;
} 

编辑1:最简测试示例仍报错

我测试了以下最简示例,但依旧抛出错误。随后尝试查询所有子窗口并反向遍历,但第一个子窗口就触发了错误。

测试代码

#include <iostream>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xresource.h>


int main(int, char**) {
    //XColor c;
    Display *display = XOpenDisplay(NULL);
    Window root = DefaultRootWindow(display);
    Window root_root, parent;
    Window *children;
    unsigned int returned_children;
    XQueryTree(display, root, &root_root, &parent, &children, &returned_children);
    for (int i = returned_children -1; i >= 0; i--) {
        std::cout << i << std::endl;
        XImage *image = XGetImage(display, root, 0, 0, 100, 100, AllPlanes, ZPixmap);
        if (image) {
            std::printf("%d %d (%p)\n", image->width, image->height, image->data);
        }
    }
}

内容的提问来源于stack exchange,提问作者thorax2077

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 13:50:48