例如,下面的程序可以正常运行: #include <Windows.h>
class MyClass : public WNDCLASSEX { protected: HWND hWnd; public: LPTSTR szTitle;
MyClass(); void Register(); void Create(int nCmdShow); int Loop();
static LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam); };
// 构造函数 MyClass::MyClass() { cbSize = sizeof(WNDCLASSEX); cbClsExtra = 0; cbWndExtra = 0; hbrBackground = CreateSolidBrush(GetSysColor(COLOR_WINDOW)); hCursor = LoadCursor(NULL, IDC_ARROW); hIcon = LoadIcon(NULL, IDI_APPLICATION); hIconSm = LoadIcon(NULL, IDI_APPLICATION); hInstance = hInstance; lpfnWndProc = WndProc; // 子类不能直接重写父类的lpfnWndProc, 否则创建窗口会失败 lpszClassName = TEXT("MyClass"); lpszMenuName = NULL; style = NULL; }
void MyClass::Register() { if (!RegisterClassEx(this)) exit(0); }
void MyClass::Create(int nCmdShow) { hWnd = CreateWindow(TEXT("MyClass"), szTitle, WS_OVERLAPPEDWINDOW, 100, 100, 640, 480, NULL, NULL, hInstance, NULL); if (!hWnd) exit(0); ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); }
int MyClass::Loop() { MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return msg.wParam; }
LRESULT CALLBACK MyClass::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, uMsg, wParam, lParam); } return FALSE; }
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MyClass cls; cls.szTitle = TEXT("窗口标题"); cls.Register(); cls.Create(nCmdShow); return cls.Loop(); }
|