#include<windows.h>
#include <time.h>
//声明WndProc()函数
#define IDC_TIMER 100
LRESULT CALLBACK WndProc(
HWND hwnd,UINT message,
WPARAM wParam,
LPARAM lParam);
//编写WinMain()主函数
int randomize();
int random(int);
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
randomize();
WNDCLASS wndclass; //定义窗口类结构变量
HWND hwnd; //定义窗口句柄
MSG msg; //定义消息结构变量
char lpszClassName[]="自己创建的窗口";
//设计窗口类型
wndclass.style = CS_HREDRAW|CS_VREDRAW; //改变窗口大小则重画
wndclass.lpfnWndProc = WndProc; //窗口函数为WndProc
wndclass.cbClsExtra = 0; //窗口类无扩展
wndclass.cbWndExtra = 0; //窗口实例无扩展
wndclass.hInstance = hInstance; //注册窗口类实例句柄
wndclass.hIcon = LoadIcon(NULL,IDI_APPLICATION); //用箭头光标
wndclass.hCursor = LoadCursor(NULL,IDC_ARROW);
wndclass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); //背景为白色
wndclass.lpszMenuName = NULL; //窗口默认无菜单
wndclass.lpszClassName =lpszClassName;
int SW_XFS = GetSystemMetrics(SM_CXSCREEN);
int SW_YFS = GetSystemMetrics(SM_CYSCREEN);
//注册窗口类型
if(! RegisterClass(&wndclass))
return FALSE;
//创建窗口
hwnd = CreateWindow(lpszClassName,
"window窗口创建",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, CW_USEDEFAULT,
NULL,
NULL,
hInstance,
NULL);
//显示并刷新窗口
ShowWindow(hwnd,nCmdShow);
//显示窗口
SetTimer(hwnd,IDC_TIMER,500,NULL);
UpdateWindow (hwnd); //更新窗口的客户区
//消息循环
while(GetMessage (&msg,NULL,0,0))
{
TranslateMessage (&msg); //键盘消息转换
DispatchMessage (&msg); //派送消息给窗口函数
}
return msg.wParam; //返回退出值
}
//响应窗口消息
LRESULT CALLBACK WndProc(HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
static RECT rect;
static int ww,wh;
HPEN hOldPen,hNewPen;
HBRUSH hOldBrush,hNewBrush;
LOGBRUSH LogBrush;
HDC hDC;
COLORREF color;
switch (message)
{
case WM_CREATE:
GetClientRect(hWnd,&rect);
ww = rect.right-rect.left;
wh = rect.bottom-rect.top;
break;
case WM_SIZE:
ww = LOWORD(lParam);
wh = HIWORD(lParam);
break;
case WM_TIMER:
hDC = GetDC(hWnd);
color = RGB(250*random(2),250*random(2),250*random(2));
hNewPen = CreatePen(PS_SOLID,0,color);
hOldPen = (HPEN)SelectObject(hDC,hNewPen);
LogBrush.lbStyle = BS_SOLID;
LogBrush.lbHatch = HS_CROSS;
LogBrush.lbColor = color;
hNewBrush = CreateBrushIndirect(&LogBrush);
hOldBrush = (HBRUSH)SelectObject(hDC,hNewBrush);
Ellipse(hDC,random(ww),random(wh),random(ww),random(wh));
hNewPen = (HPEN)SelectObject(hDC,hOldPen);
hNewBrush = (HBRUSH)SelectObject(hDC,hOldBrush);
DeleteObject(hNewPen);
DeleteObject(hNewBrush);
ReleaseDC(hWnd,hDC);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd,message,wParam,lParam);
}
return 0;
}
int randomize()
{
srand((unsigned int)time(NULL));
return 0;
}
int random(int number)
{
int rn;
rn = (int)(((long)rand()*number)/(RAND_MAX+1));
return rn;
}