簡體   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