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

时间:2018-02-17 05:13:36

标签: c linux screen screen-resolution

我知道我可以使用xdpyinfo从Linux命令行获取屏幕分辨率但是是否也可以在C程序中执行此操作?如果是这样的话?

2 个答案:

答案 0 :(得分:1)

如果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))循环就是在文件描述符关闭和复制期间防止中断。

答案 1 :(得分:1)

按照@ 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