How to use GetLastError() Function?

I wanna know why my Dialog Box creation is failing by retrieving the last error code. So I did some research and got something on http://msdn.microsoft.com/en-us/library/ms679360

MSDN has suggested the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <windows.h>
#include <strsafe.h>

void ErrorExit(LPTSTR lpszFunction) 
{ 
    // Retrieve the system error message for the last-error code

    LPVOID lpMsgBuf;
    LPVOID lpDisplayBuf;
    DWORD dw = GetLastError(); 

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER | 
        FORMAT_MESSAGE_FROM_SYSTEM |
        FORMAT_MESSAGE_IGNORE_INSERTS,
        NULL,
        dw,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
        (LPTSTR) &lpMsgBuf,
        0, NULL );

    // Display the error message and exit the process

    lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, 
        (lstrlen((LPCTSTR)lpMsgBuf)+lstrlen((LPCTSTR)lpszFunction)+40)*sizeof(TCHAR)); 
    StringCchPrintf((LPTSTR)lpDisplayBuf, 
        LocalSize(lpDisplayBuf) / sizeof(TCHAR),
        TEXT("%s failed with error %d: %s"), 
        lpszFunction, dw, lpMsgBuf); 
    MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); 

    LocalFree(lpMsgBuf);
    LocalFree(lpDisplayBuf);
    ExitProcess(dw); 
}

void main()
{
    // Generate an error

    if(!GetProcessId(NULL))
        ErrorExit(TEXT("GetProcessId"));
}


MSDN says one should link with the Kernel32.lib and use the Kernel32.dll to compile successfully. As I'm using Dev-C++, I linked with libkernel32.a but the above mentioned code is compiling with errors.

What does it mean to use the Kernel32.dll so that this code can compile successfully?

Is there any other way to retrieve the last error in order to know why the dialog box creation is failing?
All Win32 programs are automatically linked with Kernel32. Just compile and run.
That is not a GUI program - I wouldn't think that a DOS program (like yours) would be able to display a MessageBox..
As long as it is linked to the Win32 library it can do anything it wants.
Well that's told me :-))
You learn something new everyday.
Sorry I took too much time to react. I was busy with other stuff.

My compiler seems not to recognize the header file <strsafe.h>. I get "strsafe.h: No such file or directory" and " 'StringCchPrintf' undeclared (first use this function) " as errors.

Any clue what the equivalent of strsafe.h in Dev-C++ is?
Hmm, I don't know and didn't find anything with a quick google.

This page has some good stuff though (scroll about halfway down):
http://www.di-mgt.com.au/cprog.html
Thanks Duoas for troubling yourself to help. I'll have a look at the page. It seems to be worth it.
Topic archived. No new replies allowed.