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



// Rappresenta un pixel in una DIB a 24 bpp


struct DIB24BPPPixel
{
BYTE Blue;
BYTE Green;
BYTE Red;
};
try
{
// I device context
HDC dibDC=NULL, screenDC=NULL;
// Larghezza e altezza dello schermo (e di conseguenza della DIB)
LONG width, height;
// Bitmap selezionata all'inizio in dibDC, DIB Section
HBITMAP oldBmp=NULL, dibSection=NULL;
// Puntatore ai dati della DIB
LPBYTE dibBits=NULL;
// Struttura utilizzata per inizializzare la DIB
BITMAPINFO bi={0};
// Lunghezza di una riga della DIB in byte; ci torna utile averlo pronto visto che le righe devono essere allineate a 32 bit
size_t bytesPerLine=0;
// Ottiene le dimensioni dello schermo
width = (LONG) GetSystemMetrics(SM_CXFULLSCREEN);
height = (LONG) GetSystemMetrics(SM_CYFULLSCREEN);
// Calcola la lunghezza di una riga della DIB
bytesPerLine = ((width * 24 + 31) & (~31)) / 8;
// Ottiene l'handle al DC dello schermo
screenDC = GetDC(0)
if(screenDC == NULL)
throw std::runtime_error("Impossibile ottenere il DC dello schermo; GetDC ha restituito NULL.");
// Inizializza i dati della DIB
bi.bmiHeader.biSize=sizeof(bi.bmiHeader);
bi.bmiHeader.biWidth=width;
bi.bmiHeader.biHeight=height;
bi.bmiHeader.biPlanes=1;
bi.bmiHeader.biBitCount=24; /* per semplicità usiamo una DIB a 24 bpp qualunque sia la profondità di colore dello schermo */
bi.bmiHeader.biCompression=BI_RGB;
// Crea la DIB section
dibSection=CreateDIBSection(NULL, &bi, DIB_RGB_COLORS, (LPVOID *)&dibBits, NULL, 0);
if(dibSection == NULL)
throw std::runtime_error("Impossibile creare la DibSection; CreateDIBSection ha restituito NULL.");
// Crea il DC
dibDC = CreateCompatibleDC(NULL);
if(dibDC == NULL)
throw std::runtime_error("Impossibile creare il device context; CreateCompatibleDC ha restituito NULL.");
// Seleziona la DIB section nel DC e salva la bitmap di default attualmente contenuta nel DC
oldBmp = SelectObject(dibDC, dibSection);
for(/* bla bla bla */)
{
// Ciclo da ripetere per ogni controllo dello schermo
// Copia il contenuto dello schermo nella DIB section
BitBlt(dibDC, 0,0, width, height, screenDC, 0, 0, SRCCOPY);
// Qui controlla i pixel della DIB
for(int y=0; y<height; y++)
{
// Ottiene un puntatore al primo pixel della riga
DIB24BPPPixel * rowPtr = (DIB24BPPPixel *) (dibBits+(height-1-y)*bytesPerLine);
for(int x=0; x<width; x++)
{
// Verifica il colore del pixel
// Esempio:
if(rowPtr[x].Red==255 && rowPtr[x].Green==0 && rowPtr[x].Blue==0)
{
//Il pixel è rosso
}
}
}
Sleep(/* valore che ritieni più opportuno */);
/* bla bla bla */
}
// Cleanup
ReleaseDC(screenDC);
SelectObject(dibDC, oldBmp);
DeleteDC(dibDC);
DeleteObject(dibSection);
}
catch(...)
{
// Cleanup in caso di errore
if(screenDC != NULL)
ReleaseDC(screenDC);
if(dibDC != NULL)
{
SelectObject(dibDC, oldBmp);
DeleteDC(dibDC);
}
if(dibSection != NULL)
DeleteObject(dibSection);
// Propaga l'eccezione
throw;
}