Anatoly Lubarsky Logo
MSSQL, .NET, Design. Life and Music

WinAPI: How to Get Last Error from Windows API Functions Stack (GetLastError)

The following algorithm demonstrates how to get last error from Windows API functions stack. The algorithm uses 2 functions imported from kernel32: GetLastError and FormatMessage:


[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern int GetLastError();

[DllImport("kernel32.dll", CharSet=CharSet.Auto)]
public static extern int FormatMessage(int dwFlags, 
    string lpSource, 
    int dwMessageId,
    int dwLanguageId,
    StringBuilder lpBuffer,
    int nSize, 
    string[] Arguments);

The following piece of code in C# utilizes WinAPI functions defined above to get formatted error message as string:


public static string GetLastErrorMessage()
{
    StringBuilder strLastErrorMessage = new StringBuilder(255);
    int ret2 = GetLastError();
    int dwFlags = 4096;

    int ret3 = FormatMessage(dwFlags, 
        null, 
        ret2, 
        0,
        strLastErrorMessage,
        strLastErrorMessage.Capacity, 
        null);

    return strLastErrorMessage.ToString();
}

Enjoy :)


Related Posts:

Thursday, April 17, 2008 1:42 AM

If your feedback doesn't appear right away, please be patient as it may take a few minutes to publish.

Post a Comment

Protected by CAPTCHAEnter the code you see
Name (*)  
E-mail (*)  
Url
Remember

Comment (*)