在C语言中获取Windows屏幕分辨率

3

在Windows中,使用纯C语言(不是C++/C#/Objective-C),如何获取屏幕分辨率?

我的编译器是MingW(不确定是否相关)。所有我找到的解决方案都是针对C++或其他C变体的。

4个回答

6

使用GetSystemMetrics()函数。

DWORD dwWidth = GetSystemMetrics(SM_CXSCREEN);
DWORD dwHeight = GetSystemMetrics(SM_CYSCREEN);

1

适用于Linux的指南

我在Ubuntu 20.04上尝试过,它完美地工作了!

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

unsigned short *get_screen_size(void)
{
    static unsigned short size[2];
    char *array[8];
    char screen_size[64];
    char* token = NULL;

    FILE *cmd = popen("xdpyinfo | awk '/dimensions/ {print $2}'", "r");

    if (!cmd)
        return 0;

    while (fgets(screen_size, sizeof(screen_size), cmd) != NULL);
    pclose(cmd);

    token = strtok(screen_size, "x\n");

    if (!token)
        return 0;

    for (unsigned short i = 0; token != NULL; ++i) {
        array[i] = token;
        token = strtok(NULL, "x\n");
    }
    size[0] = atoi(array[0]);
    size[1] = atoi(array[1]);
    size[2] = -1;

    return size;
}


int main(void)
{
    unsigned short *size = get_screen_size();

    printf("Screen resolution = %dx%d\n", size[0], size[1]);

    return 0;
}

如果您有任何问题,请不要犹豫! :)

1

您需要在代码中包含windows.h,使用Windows API。MingW可能已经包含了这个头文件。

#include <windows.h>

void GetMonitorResolution(int *horizontal, int *vertical) {
    *height = GetSystemMetrics(SM_CYSCREEN);
    *width = GetSystemMetrics(SM_CXSCREEN);
}

0

你的问题已经被回答了:如何从hWnd获取监视器屏幕分辨率?

HMONITOR monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
MONITORINFO info;
info.cbSize = sizeof(MONITORINFO);
GetMonitorInfo(monitor, &info);
int monitor_width = info.rcMonitor.right - info.rcMonitor.left;
int monitor_height = info.rcMonitor.bottom - info.rcMonitor.top;

MONITOR_DEFAULTTONEAREST未被定义。 - Jimmay
@Jimmay,打开winuser.h并搜索一下看看它是否存在,可能只是隐藏在#ifdef后面。 - chris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接