7行砂嵐プログラミングで使ったコードの、最適化を行っていないバージョンのソースコードです。
学習用にぜひどうぞ♪
#include <windows.h>
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
PAINTSTRUCT ps;
HDC hdc;
int i;
static int r; // 乱数用
switch (message)
{
case WM_PAINT:
{
hdc = BeginPaint (hWnd, &ps);
unsigned char *bitmap;
bitmap = new unsigned char[640 * 400 * 3];
HDC hmemdc;
hmemdc = CreateCompatibleDC(hdc);
HBITMAP hb;
hb = ::CreateCompatibleBitmap(hdc, 640, 400);
BITMAPINFO bi;
// 最低でも以下の情報だけは指定する必要がある
bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bi.bmiHeader.biWidth = 640;
bi.bmiHeader.biHeight = 400;
bi.bmiHeader.biPlanes = 1;
bi.bmiHeader.biBitCount = 24;
bi.bmiHeader.biCompression = BI_RGB;
// 念のために精確なBITMAPINFOを取得しておく
GetDIBits(hmemdc, (HBITMAP)hb, 0, 400, 0, &bi, DIB_RGB_COLORS);
for(i = 0; i < 640*400*3; i += 3) {
// r:疑似乱数
// RGBすべてを同じ値にしてグレースケールにする
bitmap[i] = bitmap[i+1] = bitmap[i+2] = r>>16;
r = (r * 9 + 5);
}
// DCにコピー
SetDIBitsToDevice(hdc, 0, 0, 640, 400, 0, 0, 0, 400, bitmap, &bi, DIB_RGB_COLORS);
DeleteObject((HBITMAP)hb);
DeleteDC(hmemdc);
delete bitmap;
EndPaint(hWnd, &ps);
InvalidateRect(hWnd, NULL, false);
break;
}
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc (hWnd, message, wParam, lParam);
}
return 0;
}
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
MSG msg;
WNDCLASS wndclass;
HWND hWnd;
if (!hPrevInstance) {
// 古いWNDCLASSを使用(行数を減らすため)
wndclass.style = CS_HREDRAW|CS_VREDRAW;
wndclass.lpfnWndProc = WndProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = NULL;
wndclass.hCursor = LoadCursor(NULL,IDC_ARROW);
wndclass.hbrBackground = NULL;
wndclass.lpszClassName = "Tax";
wndclass.lpszMenuName = NULL;
if (!RegisterClass(&wndclass))
return FALSE;
}
hWnd=CreateWindow("Tax", "砂", WS_OVERLAPPED | WS_SYSMENU
, CW_USEDEFAULT, CW_USEDEFAULT, 640, 400
, NULL, NULL, hInstance, NULL);
ShowWindow(hWnd, nCmdShow);
BOOL bRet;
while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0) {
if (bRet == -1) {
return -1;
}
else {
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
return (int)msg.wParam;
}