Windows SDK: How to get the reason for a failure of a SDK function?
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 1 of 1

Thread: Windows SDK: How to get the reason for a failure of a SDK function?

Hybrid View

  1. #1
    ovidiucucu's Avatar
    ovidiucucu is offline Moderator/Reviewer Power Poster
    Join Date
    Feb 2003
    Location
    Iasi - Romania
    Posts
    8,021

    Windows SDK: How to get the reason for a failure of a SDK function?

    Q: How to get the reason for a failure of a SDK function?

    A: First of all, take a look in MSDN and read the documentation of the function. See the meaning of the returned value.

    Most Windows SDK functions return a value showing if the function succeeded or failed (in our example 0 if failed and nonzero if succeeded).

    Usually, next is written in MSDN: To get extended error information, call 'GetLastError()'.

    Code:
    BOOL bRet = CreateDirectory(_T("X:\\MyApp\\Bin\\Shared"), NULL);
    if(!bRet)
    {
      DWORD dwError = GetLastError();
      // put a breakpoint here and type the value of dwError in Error Lookup tool
    }
    Also, we can get the error text using 'FormatMessage()':

    Code:
    void ReportLastError()
    {
      LPCTSTR pszCaption = _T("Windows SDK Error Report");
      DWORD dwError      = GetLastError();
    
      if(NOERROR == dwError)
      {
        MessageBox(NULL, _T("No error"), pszCaption, MB_OK);
      }
      else
      {
        const DWORD dwFormatControl = FORMAT_MESSAGE_ALLOCATE_BUFFER |
                                      FORMAT_MESSAGE_IGNORE_INSERTS |
                                      FORMAT_MESSAGE_FROM_SYSTEM;
    
        LPVOID pTextBuffer = NULL;
        DWORD dwCount = FormatMessage(dwFormatControl, 
                                      NULL, 
                                      dwError, 
                                      0, 
                                      (LPTSTR) &pTextBuffer, 
                                      0, 
                                      NULL);
        if(0 != dwCount)
        {
          MessageBox(NULL, (LPCSTR)pTextBuffer, pszCaption, MB_OK|MB_ICONERROR);
          LocalFree(pTextBuffer);
        }
        else
        {
          MessageBox(NULL, _T("Unknown error"), pszCaption, MB_OK|MB_ICONERROR);
        }
      }
    }
    The following example shows how to use it:

    Code:
    BOOL bRet = CreateDirectory(_T("X:\\MyApp\\Bin\\Shared"), NULL);
    if(!bRet)
    {
      ReportLastError();
    }

    Last edited by ovidiucucu; January 11th, 2012 at 02:45 AM. Reason: Add a [/i] tag

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center