以下是包含的头文件
#define WIN32_LEAN_AND_MEAN // 指示编译器不要包含我们并不需要的MFC内容 #include <windows.h> // 包含所有的Windows头文件
#include <windowsx.h> // 含有许多重要的宏和常量的头文件
#include <stdio.h>
#include <math.h> #define WINDOW_CLASS_NAME "WINCLASS1"
Windows的事件循环处理消息的机制如下图:
现在我们来编写事件处理程序,因为在编写主程序时会调用这个函数
LRESULT CALLBACK WindowProc(HWND hwnd,
UINT msg,
WPARAM wparam,
LPARAM lparam)
{
PAINTSTRUCT ps; //用于WM_PAINT
HDC hdc; //处理设备上下文
switch(msg)
{
case WM_CREATE:
{
// 返回成功
return(0);
} break; case WM_PAINT:
{
//绘画窗口
hdc = BeginPaint(hwnd,&ps);
EndPaint(hwnd,&ps);
return(0);
} break; case WM_DESTROY:
{
//用于退出程序
PostQuitMessage(0);
return(0);
} break; default:break; }
return (DefWindowProc(hwnd, msg, wparam, lparam));
}
以下是主程序
int WINAPI WinMain( HINSTANCE hinstance, //hinstance是应用程序的实例句柄
HINSTANCE hprevinstance, //该参数现在已经不使用的
LPSTR lpcmdline, //是一个空值终止字符串
int ncmdshow) //它在启动过程中被传递给应用程序,带有程序窗口的信息
{
WNDCLASSEX winclass; // this will hold the class we create
HWND hwnd; // generic window handle
MSG msg; // generic message // first fill in the window class stucture
winclass.cbSize = sizeof(WNDCLASSEX);
winclass.style = CS_DBLCLKS | CS_OWNDC |
CS_HREDRAW | CS_VREDRAW;
winclass.lpfnWndProc = WindowProc;
winclass.cbClsExtra = ;
winclass.cbWndExtra = ;
winclass.hInstance = hinstance;
winclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
winclass.hCursor = LoadCursor(NULL, IDC_ARROW);
winclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH);
winclass.lpszMenuName = NULL;
winclass.lpszClassName = WINDOW_CLASS_NAME;
winclass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); // register the window class
if (!RegisterClassEx(&winclass))
return(); // create the window
if (!(hwnd = CreateWindowEx(NULL, // extended style
WINDOW_CLASS_NAME, // class
"Your Basic Window++", // title
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
,, // initial x,y
,, // initial width, height
NULL, // handle to parent
NULL, // handle to menu
hinstance,// instance of this application
NULL))) // extra creation parms
return(); while(TRUE)
{
if (PeekMessage(&msg,NULL,,,PM_REMOVE))
{
if (msg.message == WM_QUIT)
break; TranslateMessage(&msg); // 发送消息给WindowProc
DispatchMessage(&msg);
} } return(msg.wParam); }