創建一個windows應用程序,有以下基本步驟
- 創建窗口類
- 註冊窗口類
- 創建窗口
- 顯示窗口
- 消息循環
- 編寫窗口過程(消息處理函數)
代碼如下:
// Win32_01.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// 窗口類名,不要與系統的重複
LPCTSTR lpszClassName = TEXT("My First Window");
// 創建窗口類
WNDCLASS wndclass;
wndclass.style = 0;
wndclass.lpfnWndProc = WindowProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = hInstance;
wndclass.hIcon = 0;
wndclass.hCursor = 0;
wndclass.hbrBackground = (HBRUSH)COLOR_MENU;
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = lpszClassName;
// 註冊窗口類
RegisterClass(&wndclass);
// 創建窗口
HWND hwnd = CreateWindow(
lpszClassName,
TEXT("我的第N個WIN32應用程序"),
WS_OVERLAPPEDWINDOW,
100,100,400,300,
NULL,
NULL,
hInstance,
NULL
);
if (hwnd == NULL)
{
MessageBox(hwnd, TEXT("創建窗口失敗"), TEXT("錯誤"), MB_OK);
return 0;
}
// 顯示窗口
ShowWindow(hwnd, SW_SHOW);
// 消息循環
MSG msg;
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch(uMsg)
{
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}