xrandr 這個工具可以讓我們得知解析度、各個 output 的狀態(前提是驅動必須支援)。

在 shell script 中,常常針對 xrandr 的輸出去做文字的處理,來判斷現在的解析度、輸出裝置等等,但如果是從 C 程式呢?
一直用外部命令呼叫,或是 popen 等等,好像不是很好的方式。這點可以參考 xrandr.c 得到一個大概。它主要是透過 Xrandr
這個 extension 去取得相關的資訊。

因此簡化程式碼如下,可以得知 VGA 是否連接。

 

#include <stdio.h>
#include <X11/Xlib.h>
#include <X11/Xlibint.h>
#include <X11/Xproto.h>
#include <X11/Xatom.h>
#include <X11/extensions/Xrandr.h>
#include <X11/extensions/Xrender.h>     /* we share subpixel information */
#include <string.h>
#include <stdlib.h>


int
main(int argc, char** argv)
{
        char *display_name = NULL;
        int screen = -1;
        XRROutputInfo *output_info = NULL;
        Display *dpy;
        Window root;
        XRRScreenResources *res;

        char *connection[3] = { "connected", "disconnected", "unknown connection"};

        dpy = XOpenDisplay (display_name);

        if (dpy == NULL) {
                fprintf (stderr, "Can't open display %s\n", XDisplayName(display_name));
                exit (1);
        }

        screen = DefaultScreen (dpy);

        if (screen >= ScreenCount (dpy)) {
                fprintf (stderr, "Invalid screen number %d (display has %d)\n", screen, ScreenCount (dpy));
                exit (1);
        }

        root = RootWindow (dpy, screen);
        res = XRRGetScreenResources (dpy, root);
        output_info = XRRGetOutputInfo (dpy, res, res->outputs[0]);

        printf("%s\n", connection[output_info->connection]);

        return 0;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

arrow
arrow
    全站熱搜

    zxlin 發表在 痞客邦 留言(0) 人氣()