API 获得GetLastError()错误代码对应的文字信息

原文连接:https://www.cnblogs.com/jqdy/p/15079041.html

  API 函数出现错误后,通过GetLastError() 可以取得对应的错误代码。利用这个错误代码可以进一步查询到对应的文字描述信息。

  • 参数1:pszErrorString(out),信息字符串缓冲区指针
  • 参数2:cErrorString(in),参数1 缓冲区的长度
  • 参数3:dwErrorCode(in),GetLastError()获取的错误代码
  • 备注,输出格式为 :(err:数字)文字信息
  #include <Windows.h>
  #include <strsafe.h>
 1 PTSTR GetWindowsErrorString(PTSTR pszErrorString,  WORD cErrorString, DWORD dwErrorCode)
 2 {
 3     LPVOID lpMsgBuf = NULL;
 4     FormatMessage(
 5         FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
 6         NULL,
 7         dwErrorCode,
 8         MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
 9         (LPTSTR)&lpMsgBuf,
10         0,
11         NULL);
12     StringCchPrintf(
13         pszErrorString,
14         cErrorString,
15         TEXT("(err:%d)%s"),
16         dwErrorCode,
17         (LPTSTR)lpMsgBuf);
18     LocalFree(lpMsgBuf); // 释放 FormatMessage() 函数中分配的空间
19     return pszErrorString;
20 }
原文地址:https://www.cnblogs.com/jqdy/p/15079041.html