#include <Windows.h>
#include <tchar.h>
#include <math.h>
long WINAPI WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
UINT SCREEN_WIDTH = 1000;
UINT SCREEN_HEIGHT = 600;
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
TCHAR className[] = _T("serenesunny");
TCHAR windowName[] = _T("五角星");
WNDCLASS wndcls;
wndcls.cbClsExtra = 0;
wndcls.cbWndExtra = 0;
wndcls.hbrBackground = (HBRUSH)GetStockObject(WHITE_BRUSH);
wndcls.hCursor = LoadCursor(hInstance, IDC_ARROW);
wndcls.hIcon = LoadIcon(hInstance, IDI_APPLICATION);
wndcls.hInstance = hInstance;
wndcls.lpfnWndProc = WndProc;
wndcls.lpszClassName = className;
wndcls.lpszMenuName = 0;
wndcls.style = CS_HREDRAW | CS_VREDRAW;
RegisterClass(&wndcls);
HWND hWnd = CreateWindow(className, windowName, WS_OVERLAPPEDWINDOW, 0,
0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, hInstance, 0);
ShowWindow(hWnd, SW_SHOWNORMAL);
UpdateWindow(hWnd);
MSG msg;
while (GetMessage(&msg, hWnd, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.wParam;
}
#define Pi 3.1415926
double n = sin(3 * Pi / (double)10) / sin(Pi / (double)10); // 半徑之比
int ti = 0; // 旋轉變量
UINT index = 0;
UINT r[] = { (UINT)(n * 20), 20 };
float theta[] = {(float)(- Pi / 2), (float)(Pi / (float)5 - Pi / 2)};
POINT points[10];
UINT centerx = 100;
UINT centery = SCREEN_HEIGHT / 2;
long WINAPI WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
HDC hdc;
PAINTSTRUCT ps;
HBRUSH hBrush;
// HPEN hPen;
int i;
int index;
switch(message)
{
case WM_CREATE:
case WM_PAINT:
hdc = BeginPaint(hWnd, &ps);
hBrush = CreateSolidBrush(0x00ffff);
SelectObject(hdc, hBrush);
centerx = 100 + ti;
centery = SCREEN_HEIGHT / 2 - (long)(200 * sin(Pi * ti / (double)300));
for (index = 0; index < 5; index++)
{
for (i = 0; i < 2; i++)
{
points[index * 2 + i].x = (long)(centerx + r[i] * cos(theta[i] + index * 2 * Pi / 5));
points[index * 2 + i].y = (long)(centery + r[i] * sin(theta[i] + index * 2 * Pi / 5));
}
}
Polygon(hdc, points, 10); // 把五角星看成壹個10邊形,用多邊形畫法去畫
DeleteObject(hBrush);
ti += 2;
ti = ti % 600;
Sleep(20);
InvalidateRect(hWnd,NULL,1); //重繪窗口區域.
EndPaint(hWnd, &ps);
break;
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
如果出現錯誤:
LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
解決方法:
控制臺項目要使用windows子系統, 而不是console, 設置:
[Project] --> [Settings] --> 選擇"Link"屬性頁,
在Project Options中將/subsystem:console改成/subsystem:windows.