0

我正在尝试使用 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()函数显示通用错误消息而不是有效的任何错误消息 ID 到else?

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

4

2 回答 2

2

注册表功能不使用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);
}
于 2013-08-22T04:34:36.713 回答
0

尝试这个

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.");

}
于 2013-08-22T04:47:28.610 回答