- 1 year ago
Struggling with the CreatWindow function
Comment
1 / 1
The CreateWindow
function in the Windows API is used to create a window with the specified window class and styles. It can be a bit complex to use, but I'll provide you with a basic example and guide you through the essential parameters and steps involved. Here's an example of using the CreateWindow
function:
cpp#include <Windows.h>
// Window Procedure callback function
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CLOSE:
// Handle the window close event
DestroyWindow(hwnd);
break;
case WM_DESTROY:
// Handle the window destroy event
PostQuitMessage(0);
break;
default:
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
// Step 1: Register the window class
WNDCLASS wc = {0};
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = "MyWindowClass";
RegisterClass(&wc);
// Step 2: Create the window
HWND hwnd = CreateWindow(
"MyWindowClass", // Window class name
"My Window", // Window title
WS_OVERLAPPEDWINDOW, // Window style
CW_USEDEFAULT, // Initial X position
CW_USEDEFAULT, // Initial Y position
500, // Initial width
400, // Initial height
NULL, // Parent window
NULL, // Menu handle
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL)
{
// Handle error in window creation
return 1;
}
// Step 3: Display the window
ShowWindow(hwnd, nCmdShow);
// Step 4: Enter the message loop
MSG msg = {0};
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return static_cast<int>(msg.wParam);
}
Let's go through the steps involved in the above example:
Register the Window Class:
- The
WNDCLASS
structure is used to define the attributes of the window class. - Set the appropriate values for
lpfnWndProc
(window procedure),hInstance
(instance handle), andlpszClassName
(class name). - Call
RegisterClass
to register the window class.
- The
Create the Window:
- Call
CreateWindow
with the specified parameters to create the window. - Pass the window class name, window title, window style, initial position (X and Y), initial width, initial height, parent window (if any), menu handle (if any), instance handle, and additional application data.
- Call
Display the Window:
- Call
ShowWindow
to display the window. - Pass the window handle (
hwnd
) and thenCmdShow
parameter, which determines how the window is shown (e.g.,SW_SHOW
to show the window).
- Call
Enter the Message Loop:
- Use a message loop to handle messages sent to the window.
- Call
GetMessage
to retrieve the next message from the message queue. - Translate and dispatch the message using
TranslateMessage
andDispatchMessage
. - The loop continues until a WM_QUIT message is