Win32API ディスプレイモニターの情報を取得する

ディスプレイモニターの情報を取得するには、GetMonitorInfo関数を用いる。


GetMonitorInfo関数のプロトタイプは、以下の通り

BOOL GetMonitorInfo(
  _In_   HMONITOR hMonitor,
  _Out_  LPMONITORINFO lpmi
);


第一引数の hMonitor はディスプレイモニターのハンドルで、MonitorFromPoint関数を用いて取得する。

第二引数の lpmi は、MONITORINFO構造体またはMONITORINFOEX構造体へのポインタで、GetMonitorInfo関数からモニター情報を受け取る。


MONITORINFOEX構造体は、以下のように定義されている。

typedef struct tagMONITORINFOEX {
  DWORD cbSize; //構造体のサイズ。つまり、sizeof(MONITORINFOEX)
  RECT  rcMonitor;//ディスプレイモニターの矩形を表すRECT構造体
  RECT  rcWork;//仮想スクリーン座標の作業領域の矩形を表すRECT構造体
  DWORD dwFlags;//ディスプレイモニターの属性
  TCHAR szDevice[CCHDEVICENAME];//使用中のモニター名
} MONITORINFOEX, *LPMONITORINFOEX;





GetMonitorInfoの使用例
MonitorFromPoint関数で、座標が(100, 100)の位置のモニターのハンドルを取得する。このハンドルをetMonitorInfo関数の第一引数に指定することで、モニター情報を取得する。シングルモニターの場合とデュアルモニターの場合は、MonitorFromPoint関数に指定する座標次第で結果が異なってくるであろう。

#include <windows.h>
#include <stdio.h>

int main()
{
    HMONITOR hMonitor;
    MONITORINFOEX  MonitorInfoEx;
    POINT pt = { 100, 100 };

    //ptで指定した部分のモニターのハンドルを取得する
    hMonitor = MonitorFromPoint(pt, MONITOR_DEFAULTTONEAREST);
    
    //モニター情報を取得する
    MonitorInfoEx.cbSize = sizeof(MonitorInfoEx);
    GetMonitorInfo(hMonitor, &MonitorInfoEx);
    
    //モニター情報を表示する
    printf("rcMonitor.bottom = %d\n", MonitorInfoEx.rcMonitor.bottom);
    printf("rcMonitor.left = %d\n", MonitorInfoEx.rcMonitor.left);
    printf("rcMonitor.right = %d\n", MonitorInfoEx.rcMonitor.right);
    printf("rcMonitor.top = %d\n", MonitorInfoEx.rcMonitor.top);

    printf("rcWork.bottom = %d\n", MonitorInfoEx.rcWork.bottom);
    printf("rcWork.left = %d\n", MonitorInfoEx.rcWork.left);
    printf("rcWork.right = %d\n", MonitorInfoEx.rcWork.right);
    printf("rcWork.top = %d\n", MonitorInfoEx.rcWork.top);

    if (MonitorInfoEx.dwFlags == MONITORINFOF_PRIMARY) {
        puts("This is Primary Monitor");
    } else {
        puts("This is not Primary Monitor");
    }

    _tprintf(TEXT("szDevice = %s\n"), MonitorInfoEx.szDevice);

    return 0;
}



実行結果

rcMonitor.bottom = 1050
rcMonitor.left = 0
rcMonitor.right = 1680
rcMonitor.top = 0
rcWork.bottom = 1010
rcWork.left = 0
rcWork.right = 1680
rcWork.top = 0
This is Primary Monitor
szDevice = \\.\DISPLAY1





参考

MonitorFromPoint http://msdn.microsoft.com/ja-jp/library/cc410472.aspx

GetMonitorInfo http://msdn.microsoft.com/en-us/library/windows/desktop/dd144901(v=vs.85).aspx

MONITORINFOEX http://msdn.microsoft.com/en-us/library/windows/desktop/dd145066(v=vs.85).aspx