Windows API โ Basics
Overview
The Windows API (also known as WinAPI) is the core set of programming interfaces used to develop native Windows applications. It provides functions for:
- Creating and managing windows and controls
- Interacting with the file system
- Handling input devices
- Multithreading and synchronization
- Graphics and GDI/GDI+
- System services and security
Getting Started
To start using the Windows API in a C/C++ project:
- Install Visual Studio (Community edition works fine).
- Create a new Windows Desktop Application project.
- Include
windows.hin your source files. - Link against
User32.lib,Kernel32.lib, etc., which Visual Studio does automatically for a Windows subsystem target.
Hello World Example
The classic minimal Windows application that creates a window and displays "Hello, World!" in its client area.
#include <windows.h>
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {
switch (msg) {
case WM_PAINT: {
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
TextOutA(hdc, 10, 10, "Hello, World!", 13);
EndPaint(hwnd, &ps);
return 0;
}
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(hwnd, msg, wParam, lParam);
}
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR lpCmdLine, int nShowCmd) {
const char CLASS_NAME[] = "SampleWindowClass";
WNDCLASS wc = {0};
wc.lpfnWndProc = WndProc;
wc.hInstance = hInst;
wc.lpszClassName = CLASS_NAME;
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
RegisterClass(&wc);
HWND hwnd = CreateWindowEx(
0,
CLASS_NAME,
"Hello World - WinAPI",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, 400, 300,
NULL, NULL, hInst, NULL
);
if (hwnd == NULL) return 0;
ShowWindow(hwnd, nShowCmd);
UpdateWindow(hwnd);
MSG msg = {0};
while (GetMessage(&msg, NULL, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int)msg.wParam;
}
Common Structures
| Structure | Description |
|---|---|
WNDCLASS | Defines a window class. |
MSG | Message structure used in the message loop. |
PAINTSTRUCT | Contains information for painting a window. |
RECT | Defines a rectangle. |