使用CreateWindow函数的例子?
时间: 2024-04-30 09:23:30 浏览: 68
C语言创建windows窗口实例
以下是使用CreateWindow函数创建窗口的示例代码:
```c++
#include <windows.h>
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// Step 1: Register the Window Class
WNDCLASS wc = { 0 };
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND);
wc.lpszClassName = "MyWindowClass";
RegisterClass(&wc);
// Step 2: Create the Window
HWND hwnd = CreateWindow(
"MyWindowClass", // Name of window class to use
"Hello, World!", // Title of window
WS_OVERLAPPEDWINDOW, // Style of window
CW_USEDEFAULT, // X position of window
CW_USEDEFAULT, // Y position of window
CW_USEDEFAULT, // Width of window
CW_USEDEFAULT, // Height of window
NULL, // Handle to parent window (none)
NULL, // Handle to menu (none)
hInstance, // Handle to application instance
NULL // Additional data (none)
);
// Step 3: Show and Update the Window
ShowWindow(hwnd, nCmdShow);
UpdateWindow(hwnd);
// Step 4: Run the Message Loop
MSG msg = { 0 };
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
// Step 5: Unregister the Window Class
UnregisterClass("MyWindowClass", hInstance);
return (int)msg.wParam;
}
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, msg, wParam, lParam);
}
return 0;
}
```
在此示例中,我们首先注册了一个名为"MyWindowClass"的窗口类,然后使用CreateWindow函数创建了一个窗口,并指定了窗口的标题、样式、位置和大小等信息。接下来,我们显示和更新了窗口,并运行了一个消息循环,以便响应用户的输入事件。最后,我们在窗口关闭时注销了窗口类。窗口过程函数WndProc负责处理窗口事件,例如当用户关闭窗口时,它会发送WM_DESTROY消息给窗口程序,这个程序会调用PostQuitMessage函数来退出消息循环并关闭应用程序。
阅读全文