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

求助:在Fedora Linux的GTK3应用中用C获取显示器像素分辨率

解决Fedora GTK3应用中C语言获取显示器分辨率的问题

原代码的问题

你用xdpyinfo的方式有两个核心问题:

  • 依赖X11工具且不兼容Wayland:Fedora现在默认使用Wayland会话,xdpyinfo是X11专属工具,Wayland环境下无法运行,且系统默认未预装(需手动安装xorg-x11-utils包)。
  • 空指针处理缺陷:当popen失败(比如命令不存在)时,函数返回0,main函数直接访问size[0]会触发段错误。

适合GTK3应用的正确实现

GTK3本身提供了跨X11/Wayland的显示器信息API,无需调用外部命令,直接使用GDK封装的接口即可。以下是完整可运行代码:

#include <gtk/gtk.h>

typedef struct {
    int width;
    int height;
} ScreenResolution;

ScreenResolution get_primary_monitor_resolution(void) {
    ScreenResolution res = {0, 0};
    // GTK3应用必须先初始化才能使用GDK接口
    gtk_init(NULL, NULL);
    
    GdkDisplay *display = gdk_display_get_default();
    if (!display) {
        return res;
    }
    
    // 优先获取主显示器,不存在则取第一个显示器
    GdkMonitor *monitor = gdk_display_get_primary_monitor(display);
    if (!monitor) {
        monitor = gdk_display_get_monitor(display, 0);
    }
    
    if (monitor) {
        GdkRectangle geom;
        // 获取显示器原生像素分辨率(不考虑HiDPI缩放)
        gdk_monitor_get_geometry(monitor, &geom);
        res.width = geom.width;
        res.height = geom.height;
        
        // 如果需要适配HiDPI屏幕,可启用以下代码获取实际物理像素:
        // int scale = gdk_monitor_get_scale_factor(monitor);
        // res.width = geom.width * scale;
        // res.height = geom.height * scale;
    }
    
    return res;
}

int main(void) {
    ScreenResolution res = get_primary_monitor_resolution();
    
    if (res.width > 0 && res.height > 0) {
        printf("屏幕分辨率 = %dx%d\n", res.width, res.height);
    } else {
        fprintf(stderr, "无法获取屏幕分辨率\n");
        return 1;
    }
    
    return 0;
}

编译步骤

  1. 先安装GTK3开发依赖包:
sudo dnf install gtk3-devel
  1. 编译代码:
gcc -o screen-res screen-res.c `pkg-config --cflags --libs gtk+-3.0`

GNOME等GTK桌面环境获取屏幕尺寸的原理

GNOME这类基于GTK的桌面环境,本质是通过GDK提供的统一抽象接口获取屏幕信息:

  • GDK会自动适配当前显示后端(X11或Wayland):
    • X11会话下,GDK调用Xlib的XGetGeometry、XRRGetScreenResources等底层接口获取显示器数据;
    • Wayland会话下,GDK通过Wayland协议的wl_output接口获取分辨率、缩放因子等信息;
  • 桌面环境无需直接与底层显示协议交互,只需调用gdk_monitor_*系列API即可,这些API已经封装了跨后端的兼容逻辑。

补充:全屏窗口实现

如果你要开发全屏软件,获取分辨率后可直接用GTK API设置窗口全屏:

// 创建窗口实例后调用
gtk_window_fullscreen(GTK_WINDOW(window));

也可指定某台显示器全屏:

gtk_window_fullscreen_on_monitor(GTK_WINDOW(window), monitor);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 19:22:31