【问题标题】:How to use the GetLastError function in a Win32 Console Application?如何在 Win32 控制台应用程序中使用 GetLastError 函数?
【发布时间】:2013-08-22 04:22:05
【问题描述】:

我正在尝试使用 Windows API 中的 RegOpenKeyEx 函数打开注册表项,并使用以下代码:

#include <windows.h>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

using namespace std;

int  wmain(int argc, wchar_t*argv [])
{
    HKEY hKey = HKEY_CURRENT_USER;
    LPCTSTR lpSubKey = L"Demo";
    DWORD ulOptions = 0;
    REGSAM samDesired = KEY_ALL_ACCESS;
    HKEY phkResult;

    long R = RegOpenKeyEx(hKey, lpSubKey, ulOptions, samDesired, &phkResult);

    if (R == ERROR_SUCCESS)
    {
        cout << "The registry key has been opened." << endl;
    }
    else //How can I retrieve the standard error message using GetLastError() here?
    {

    }

}

如何使用GetLastError() 函数在else 中显示一般错误消息而不是有效的任何错误消息ID?

编辑:我知道有一个 FormatMessage 函数但有同样的问题,我不知道如何在我的代码中使用它。

【问题讨论】:

  • 是的,但是如何在我的示例代码中使用 FormatMessage?
  • 在您编辑问题之前,我的评论是有意义的。下次请尝试更具体。

标签: winapi


【解决方案1】:

注册表函数不使用GetLastError()。它们直接返回实际的错误代码:

long R = RegOpenKeyEx(hKey, lpSubKey, ulOptions, samDesired, &phkResult);

if (R == ERROR_SUCCESS)
{
    cout << "The registry key has been created." << endl;
}
else
{
    cout << "The registry key has not been created. Error: " << R << endl;
}

如果您想显示系统错误消息,请使用FormatMessage()

long R = RegOpenKeyEx(hKey, lpSubKey, ulOptions, samDesired, &phkResult);

if (R == ERROR_SUCCESS)
{
    cout << "The registry key has been created." << endl;
}
else
{
    char *pMsg = NULL;

    FormatMessageA(
        FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_ALLOCATE_BUFFER,
        NULL,
        R,
        0,
        (LPSTR)&pMsg,
        0,
        NULL
    );

    cout << "The registry key has not been created. Error: (" << R << ") " << pMsg << endl;

    LocalFree(pMsg);
}

【讨论】:

  • 太棒了!非常感谢,@Remy
【解决方案2】:

试试这个

HKEY hKey = HKEY_CURRENT_USER;
LPCTSTR lpSubKey = L"Demo";
DWORD ulOptions = 0;
REGSAM samDesired = KEY_ALL_ACCESS;
HKEY phkResult;


char *ErrorMsg= NULL;

long R = RegOpenKeyEx(hKey, lpSubKey, ulOptions, samDesired, &phkResult);

if (R == ERROR_SUCCESS)
{

    printf("The registry key has been opened.");
}
else //How can I retrieve the standard error message using GetLastError() here?
{
     FormatMessageA(
    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS |       FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_ALLOCATE_BUFFER,
    NULL,
    R,
    0,
    (LPSTR)&ErrorMsg,
    0,
    NULL
);

      printf("Error while creating Reg key.");

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-30
    • 2010-11-04
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    相关资源
    最近更新 更多