Overview
The Win32 API provides a rich set of functions for creating and managing processes and threads. This page covers the most commonly used functions, best‑practice patterns, and live code examples.
Create a Process
Use CreateProcess for full control over the new process. Below is a minimal example in C++.
C++
Explanation
#include <windows.h>
#include <iostream>
int main() {
STARTUPINFO si = { sizeof(si) };
PROCESS_INFORMATION pi;
// Command line to execute
const wchar_t* cmd = L"notepad.exe";
BOOL ok = CreateProcessW(
nullptr, // Application name
(LPWSTR)cmd, // Command line
nullptr, nullptr, // Process & thread security
FALSE, // Inherit handles?
0, // Creation flags
nullptr, nullptr, // Environment & starting directory
&si, &pi);
if (!ok) {
std::wcerr << L"CreateProcess failed: " << GetLastError() << std::endl;
return 1;
}
std::wcout << L"Process started with PID " << pi.dwProcessId << std::endl;
// Wait for the process to exit
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return 0;
}
Key points:
STARTUPINFOcontrols window appearance and handles.PROCESS_INFORMATIONreceives process and thread handles/IDs.- Always close the handles when you’re done to avoid leaks.
- Check
GetLastErrorfor detailed failure reasons.
Create a Thread
Use CreateThread or _beginthreadex for C/C++ programs. Here’s a simple example that prints numbers.
C++
Explanation
#include <windows.h>
#include <iostream>
DWORD WINAPI Counter(LPVOID param) {
int limit = *(int*)param;
for (int i = 1; i <= limit; ++i) {
std::cout << "Thread: " << i << std::endl;
Sleep(200);
}
return 0;
}
int main() {
int count = 10;
HANDLE hThread = CreateThread(
nullptr, // default security
0, // default stack size
Counter, // thread function
&count, // parameter
0, // run immediately
nullptr); // thread identifier
if (!hThread) {
std::cerr << "CreateThread failed: " << GetLastError() << std::endl;
return 1;
}
std::cout << "Main thread continues..." << std::endl;
WaitForSingleObject(hThread, INFINITE);
CloseHandle(hThread);
return 0;
}
Tips:
- Pass a pointer to data you need inside the thread (must remain valid).
- Always join with
WaitForSingleObjector close the handle if you don’t need to wait. - For C++11 and later, consider
std::threadwhich wraps the Win32 API.
Common Functions
| Function | Purpose | Header |
|---|---|---|
| CreateProcess | Create a new process with full control. | windows.h |
| CreateThread | Start a new thread in the current process. | windows.h |
| ExitProcess | Terminate the current process. | windows.h |
| TerminateThread | Forcefully end a thread (use with care). | windows.h |
| WaitForSingleObject | Wait for a handle (process/thread) to become signaled. | windows.h |