マウスで円を描くコード
「猫でもわかるWindowsプログラミング」より
↓こんな感じ。
#include <windows.h> LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); ATOM InitApp(HINSTANCE); BOOL InitInstance(HINSTANCE, int); void DrawRect(HWND, POINTS, POINTS); TCHAR szClassName[] = TEXT("Mouse1"); POINTS start, end, old_end; //Start and End point of Rectangle //windows prgram entry point int WINAPI WinMain(HINSTANCE hCurInst, HINSTANCE hPrevInst, LPSTR lpsCmdLine, int nCmdShow) { MSG msg; BOOL bRet; if(!InitApp(hCurInst)) return FALSE; if(!InitInstance(hCurInst, nCmdShow)) return FALSE; //Get Message while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0){ if (bRet == -1){ break; }else{ TranslateMessage(&msg); DispatchMessage(&msg); } } return (int)msg.wParam; } //register window class ATOM InitApp(HINSTANCE hInst) { WNDCLASSEX wc; wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInst; wc.hIcon = NULL; wc.hCursor = (HCURSOR)LoadImage( NULL, MAKEINTRESOURCE(IDC_ARROW), IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED); wc.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = szClassName; wc.hIconSm = NULL; return (RegisterClassEx(&wc)); } //Generage Window BOOL InitInstance(HINSTANCE hInst, int nCmdShow) { HWND hWnd; hWnd = CreateWindow(szClassName, //Class Name TEXT("Neko demo Mouse"), //Window Name WS_OVERLAPPEDWINDOW, //Window Style CW_USEDEFAULT, //x position CW_USEDEFAULT, //y position CW_USEDEFAULT, //Window Width CW_USEDEFAULT, //Window Height NULL, NULL, hInst, NULL, ); if (!hWnd) return FALSE; ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } //Window Procedure LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wp, LPARAM lp) { TCHAR szBuf[32]; HDC hdc; HBRUSH hBrush; static BOOL bDraw; switch (msg){ case WM_LBUTTONDOWN: bDraw = TRUE; old_end = start = MAKEPOINTS(lp); DrawRect(hWnd, start, old_end); break; case WM_MOUSEMOVE: if(bDraw){ end = MAKEPOINTS(lp); DrawRect(hWnd, start, old_end); DrawRect(hWnd, start, end); old_end = end; }else{ return DefWindowProc(hWnd, msg, wp, lp); } break; case WM_LBUTTONUP: if(bDraw){ SetCursor(LoadCursor(NULL, IDC_ARROW)); DrawRect(hWnd, start, end); bDraw = FALSE; wsprintf(szBuf, TEXT("(%d, %d) - (%d, %d)"), start.x, start.y, end.x, end.y); SetWindowText(hWnd, szBuf); hdc = GetDC(hWnd); hBrush = (HBRUSH)GetStockObject(NULL_BRUSH); SelectObject(hdc, hBrush); Ellipse(hdc, start.x, start.y, end.x, end.y); ReleaseDC(hWnd, hdc); }else{ return DefWindowProc(hWnd, msg, wp, lp); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return (DefWindowProc(hWnd, msg, wp, lp)); } return 0; } void DrawRect(HWND hWnd, POINTS beg, POINTS end) { HDC hdc; hdc = GetDC(hWnd); SetROP2(hdc, R2_NOT); MoveToEx(hdc, beg.x, beg.y, NULL); LineTo(hdc, end.x, beg.y); LineTo(hdc, end.x, end.y); LineTo(hdc, beg.x, end.y); LineTo(hdc, beg.x, beg.y); LineTo(hdc, end.x, end.y); ReleaseDC(hWnd, hdc); return; }