繁体   English   中英

是否可以在Linux下的C程序中找到屏幕分辨率?

[英]Is it possible to find the screen resolution from within a C program under Linux?

我知道我可以使用xdpyinfo从Linux上的命令行获取屏幕分辨率,但是也可以从C程序中执行此操作吗? 如果可以,怎么办?

如果xdpyinfo为您工作,请使用它。 创建一些管道, fork() ,连接管道和exec(xdpyinfo)这比找出libX11容易得多。 有人已经为您完成了这项工作。 这不是我要使用的惯用语,但可以使您理解:

int filedes[2];
if (pipe(filedes) == -1) {
  perror("pipe");
  exit(1);
}

pid_t pid = fork();
if (pid == -1) {
  perror("fork");
  exit(1);
} else if (pid == 0) {
  while ((dup2(filedes[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {}
  close(filedes[1]);
  close(filedes[0]);
  execl(cmdpath, cmdname, (char*)0);
  perror("execl");
  _exit(1);
}
close(filedes[1]);

while(...EINTR))循环仅在文件描述符关闭和复制期间防止中断。

遵循@Pablo的建议(感谢Pablo!),我能够破解xdpyinfo.c以获得我想要的东西。 演示代码为:

#ifdef WIN32
#include <X11/Xwindows.h>
#endif

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

static void
print_screen_info(Display *dpy, int scr)
{
    /*
     * there are 2.54 centimeters to an inch; so there are 25.4 millimeters.
     *
     *     dpi = N pixels / (M millimeters / (25.4 millimeters / 1 inch))
     *         = N pixels / (M inch / 25.4)
     *         = N * 25.4 pixels / M inch
     */

    double xres, yres;

    xres = ((((double) DisplayWidth(dpy,scr)) * 25.4) /
            ((double) DisplayWidthMM(dpy,scr)));
    yres = ((((double) DisplayHeight(dpy,scr)) * 25.4) /
            ((double) DisplayHeightMM(dpy,scr)));

    printf ("\n");
    printf ("screen #%d:\n", scr);
    printf ("  dimensions:    %dx%d pixels (%dx%d millimeters)\n",
            XDisplayWidth (dpy, scr),  XDisplayHeight (dpy, scr),
            XDisplayWidthMM(dpy, scr), XDisplayHeightMM (dpy, scr));
    printf ("  resolution:    %dx%d dots per inch\n",
            (int) (xres + 0.5), (int) (yres + 0.5));
}


int
main(int argc, char *argv[])
{
    Display *dpy;                        /* X connection */
    char *displayname = NULL;            /* server to contact */
    int i;                      

    dpy = XOpenDisplay (displayname);
    if (!dpy) {
        fprintf (stderr, "unable to open display \"%s\".\n",
                 XDisplayName (displayname));
        exit (1);
    }

    printf ("name of display:    %s\n", DisplayString (dpy));
    printf ("default screen number:    %d\n", DefaultScreen (dpy));
    printf ("number of screens:    %d\n", ScreenCount (dpy));

    for (i = 0; i < ScreenCount (dpy); i++) {
        print_screen_info (dpy, i);
    }

    XCloseDisplay (dpy);
    exit (0);
}

编译:

gcc test.c -lX11

输出如下:

erpsim1:~/linux_lib/test> ./a.out 
name of display:    localhost:15.0
default screen number:    0
number of screens:    1

screen #0:
  dimensions:    4400x1400 pixels (1552x494 millimeters)
  resolution:    72x72 dots per inch

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM