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

size_t GetSizeFromDim(int x, int y);

typedef struct {
    DWORD dwSize;
    WORD  wRes1;
    WORD  wRes2;
    DWORD dwOffset;
    DWORD dwHeaderSize;
    DWORD dwWidth;
    DWORD dwHeight;
    WORD  wFoo;
    WORD  wBitsPerPixels;
    DWORD dwCompressed;
    DWORD dwBytesPerPixels;
    DWORD dwBitsPerMetterOnWidth;
    DWORD dwBitsPerMetterOnHeigt;
    DWORD dwNumberOfColors;
    DWORD dwImportantColors;
} BMPHDR, *PBMPHDR;

typedef struct {
    char bBlue, bGreen, bRed;
} PIXEL, *PPIXEL;


int main(int argc, char **argv) {

    BMPHDR Hdr;
    Hdr.dwSize                 = GetSizeFromDim(GetSystemMetrics(SM_CXFULLSCREEN), GetSystemMetrics(SM_CYFULLSCREEN));
    Hdr.wRes1                  = 0x0000;
    Hdr.wRes2                  = 0x0000;
    Hdr.dwOffset               = 0x00000036;
    Hdr.dwHeaderSize           = 0x00000028;
    Hdr.dwWidth                = (DWORD)GetSystemMetrics(SM_CXSCREEN);
    Hdr.dwHeight               = (DWORD)GetSystemMetrics(SM_CYSCREEN);
    Hdr.wFoo                   = 0x0001;
    Hdr.wBitsPerPixels         = 0x0018;
    Hdr.dwCompressed           = 0;
    Hdr.dwBytesPerPixels       = 0x00000004;
    Hdr.dwBitsPerMetterOnWidth = 0;
    Hdr.dwBitsPerMetterOnHeigt = 0;
    Hdr.dwNumberOfColors       = 0;
    Hdr.dwImportantColors      = 0;

    WORD Sign = 0x4d42;

    // Fichier de sortie
    FILE *fout = fopen("foo.bmp","wb");
    fwrite(&Sign, sizeof(WORD), 1, fout);
    fwrite(&Hdr, sizeof(BMPHDR), 1, fout);



    // Récupération du handle de l'écran
    HDC ecran = GetDC(NULL);

    // Lecture des pixels et enregistrement !
    COLORREF Color;
    PIXEL Pixel;
    int i, j, k;

    char bourrage = 0;

    for(j = Hdr.dwHeight - 1; j >= 0; j--) {

        // Un bmp part du bas, donc on lira les pixels à partir du bas
        for(i = 0; i < Hdr.dwWidth; i++) {
            Color        = GetPixel(ecran, i, j);
            Pixel.bBlue  = GetBValue(Color);
            Pixel.bGreen = GetGValue(Color);
            Pixel.bRed   = GetRValue(Color);

            // Ecriture du pixel
            fwrite(&Pixel, sizeof(PIXEL), 1, fout);
        }
        // On bourre
        for(k = 0; k < (i % 4); k++)
            fwrite(&bourrage, sizeof(char), 1, fout);
    }

    fclose(fout);

    return 0;
}

size_t GetSizeFromDim(int x, int y) {
    return sizeof(BMPHDR) + ((x*3 + (x%4))*y);
}