You are currently viewing C Programming 101: How to Get Screen Dimensions

C Programming 101: How to Get Screen Dimensions

Have you ever wondered what the dimensions of your computer screen are? Maybe you need to know in order to optimize an application or game, or perhaps you’re just curious. It turns out that with just a few lines of code in C, you can obtain the width and height of your screen using the GetSystemMetrics function from the Windows API, as demonstrated in the example code below. Be aware that this only works on Windows computers!

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

int main() {

    /* get screen width */
    int width = GetSystemMetrics(SM_CXSCREEN);

    /* get screen height */
    int height = GetSystemMetrics(SM_CYSCREEN);

    if (width == 0 || height == 0) {
        fprintf(stderr, "Failed to retrieve screen dimensions.\n");
        return 1;
    }

    /* print screen dimensions out to the console */
    printf("{width: %d, height: %d}\n", width, height);

    return 0;

}

When above code is executed, it displays the dimensions of your computer screen to the console. I do hope you find this informative. If you wish to learn more about C, please subscribe to our newsletter today and continue your C learning journey with us!

Leave a Reply