Linux环境下C++实现关闭双显示器中单台的方法求助
如何在Linux下用C++单独关闭一台显示器
嘿,我懂你现在的烦恼——直接用DPMS全局调用会把所有显示器都关掉,确实不是你想要的效果。要单独控制某一台显示器,咱们得借助X RandR扩展,它能让咱们精准操作每个显示输出设备,而不是一刀切。
核心思路
DPMS的全局调用是给整个显示服务器发指令,而RandR可以让我们定位到具体的某个显示器(比如HDMI-1、DP-1这类输出端口),然后单独给这个端口设置DPMS关闭状态。
完整代码示例
下面的代码会枚举所有显示输出,找到你指定名字的显示器,然后关闭它:
#include <X11/Xlib.h> #include <X11/extensions/Xrandr.h> #include <iostream> #include <cstring> int main() { // 打开显示连接 Display* dpy = XOpenDisplay(nullptr); if (!dpy) { std::cerr << "Failed to open display!" << std::endl; return 1; } int screen = DefaultScreen(dpy); Window root_window = RootWindow(dpy, screen); // 检查是否支持RandR扩展 int rr_major_ver, rr_minor_ver; if (!XRRQueryVersion(dpy, &rr_major_ver, &rr_minor_ver)) { std::cerr << "RandR extension not supported!" << std::endl; XCloseDisplay(dpy); return 1; } // 获取当前屏幕的所有输出资源 XRRScreenResources* screen_res = XRRGetScreenResourcesCurrent(dpy, root_window); if (!screen_res) { std::cerr << "Failed to get screen resources!" << std::endl; XCloseDisplay(dpy); return 1; } bool target_found = false; const char* target_display_name = "HDMI-1"; // 替换成你要关闭的显示器名字 // 遍历所有输出设备 for (int i = 0; i < screen_res->noutput; ++i) { RROutput output = screen_res->outputs[i]; XRROutputInfo* output_info = XRRGetOutputInfo(dpy, screen_res, output); if (!output_info) continue; // 匹配目标显示器名字 if (strcmp(output_info->name, target_display_name) == 0) { // 设置该输出的DPMS状态为关闭 Atom dpms_mode_atom = XInternAtom(dpy, "DPMS_MODE", False); XRRSetOutputProperty(dpy, output, dpms_mode_atom, XA_INTEGER, 32, PropModeReplace, (unsigned char*)&DPMSModeOff, 1); target_found = true; std::cout << "Successfully turned off display: " << target_display_name << std::endl; XRRFreeOutputInfo(output_info); break; } XRRFreeOutputInfo(output_info); } if (!target_found) { std::cerr << "Target display not found: " << target_display_name << std::endl; } // 同步修改到X服务器 XSync(dpy, False); // 释放资源 XRRFreeScreenResources(screen_res); XCloseDisplay(dpy); return 0; }
编译与运行
编译时需要链接X11和RandR库:
g++ -o close_single_display close_single_display.cpp -lX11 -lXrandr
运行前,你需要先知道目标显示器的名字——在终端输入xrandr命令,就能看到所有已连接的显示器名称(比如HDMI-1、DP-2等),把代码里的target_display_name替换成对应的名字即可。
注意事项
- 部分桌面环境(比如GNOME、KDE)自带的电源管理可能会覆盖DPMS设置,如果遇到程序执行后显示器又自动亮起的情况,可以暂时调整桌面环境的电源休眠设置。
- 程序需要当前用户有访问X显示的权限,一般本地登录用户都没问题,远程桌面场景可能需要额外配置
DISPLAY环境变量。
内容的提问来源于stack exchange,提问作者Mitski_fys
相关产品推荐
相关产品推荐

