GetLastError function
The GetLastError function retrieves the calling thread's last-error code value. This function is often used to obtain extended error information after a Windows API call fails.
Header
#include <windows.h>
Library
Kernel32.lib
Syntax
DWORD WINAPI GetLastError(void);
Return Value
Returns the calling thread's last-error code. The value is of type DWORD. If the function succeeds, the return value is zero.
Remarks
- The last-error code is maintained on a per‑thread basis.
- Many Windows API functions set the last-error value when they fail. Call
GetLastErrorimmediately after the function that failed. - Do not call
SetLastErrorunless you are explicitly resetting the error code. - When writing multithreaded code, ensure you call
GetLastErrorfrom the same thread that called the failing API.
Example
Note: This example demonstrates retrieving the error code after a failed
DeleteObject call.
#include <windows.h>
#include <stdio.h>
int main(void)
{
HBITMAP hBmp = CreateBitmap(0, 0, 1, 1, NULL);
if (!hBmp)
{
printf("CreateBitmap failed. Error: %lu\\n", GetLastError());
return 1;
}
// Intentional error: DeleteObject expects a GDI object, not a handle to a bitmap created with zero dimensions.
if (!DeleteObject((HGDIOBJ)hBmp))
{
DWORD err = GetLastError();
printf("DeleteObject failed. Error: %lu\\n", err);
}
return 0;
}