【Escapist:003】C++ 仅仅使用 Windows API 创建一个窗口
仅仅使用 Windows API 创建一个窗口,并且让它显示在屏幕中央。代码:
程序代码:
#include<Windows.h> #pragma comment(linker, "/manifestdependency:\"type='win32' name='Microsoft.' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") const char WindowClassName[] = "WindowClass"; const char WindowCaption[] = "CreateWindowExA"; HINSTANCE InstanceHandle; //HWND WindowHandle; long __stdcall WindowProcess(HWND WindowHandle, unsigned int Message, unsigned int wParam, long lParam); int __stdcall WinMain(HINSTANCE hInstance, HINSTANCE PreInstanceHandle, char* lpCmdLine, int nCmdShow) { InstanceHandle = hInstance; WNDCLASSEXA WindowClass; WindowClass.cbSize = sizeof(WNDCLASSEXW); WindowClass.style = CS_HREDRAW | CS_VREDRAW; WindowClass.lpfnWndProc = WindowProcess; WindowClass.cbClsExtra = 0; WindowClass.cbWndExtra = 0; WindowClass.hInstance = InstanceHandle; WindowClass.hIcon = LoadIconA(InstanceHandle, NULL); WindowClass.hCursor = LoadCursorA(InstanceHandle, MAKEINTRESOURCEA(32512)); WindowClass.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); WindowClass.lpszMenuName = NULL; WindowClass.lpszClassName = WindowClassName; WindowClass.hIconSm = LoadIconA(InstanceHandle, NULL); RegisterClassExA(&WindowClass); HWND WindowHandle = CreateWindowExA(WS_EX_CLIENTEDGE, WindowClassName, WindowCaption, WS_OVERLAPPEDWINDOW, 0, 0, 750, 500, NULL, NULL, InstanceHandle, NULL); if (!WindowHandle) return 0; ShowWindow(WindowHandle, SW_SHOW); MSG Message; while (GetMessageA(&Message, nullptr, 0, 0)) { TranslateMessage(&Message); DispatchMessageA(&Message); } return 0; } long __stdcall WindowProcess(HWND WindowHandle, unsigned int Message, unsigned int wParam, long lParam) { switch (Message) { case WM_CREATE: { RECT Rect; GetWindowRect(WindowHandle, &Rect); SetWindowPos(WindowHandle, HWND_TOP, ((GetSystemMetrics(SM_CXSCREEN) - Rect.right) / 2), ((GetSystemMetrics(SM_CYSCREEN) - Rect.bottom) / 2), Rect.right, Rect.bottom, SWP_SHOWWINDOW); break; } case WM_PAINT: { PAINTSTRUCT PaintStruct; HDC DCHandle = BeginPaint(WindowHandle, &PaintStruct); //添加绘图代码 EndPaint(WindowHandle, &PaintStruct); break; } case WM_DESTROY: { PostQuitMessage(0); break; } default: { return DefWindowProcA(WindowHandle, Message, wParam, lParam); } } return 0; }
Main.rar
(1.08 KB)
将代码拷贝到空白cpp文件中即可运行。
如果反响较高,我会详细出几期教程,谢谢~