2013-08-22 26 views
0

我試圖打開使用RegOpenKeyEx函數從Windows API註冊表項,並有這樣的代碼:如何在Win32控制檯應用程序中使用GetLastError函數?

#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函數,但有同樣的問題,我不知道如何使用它在我的代碼。

+0

[的FormatMessage(HTTP ://msdn.microsoft.com/en-us/library/windows/apps/ms679351(v = vs.85).aspx) – Noseratio

+0

是的,但我如何使用我的示例代碼中的FormatMessage? –

+0

我的評論是有道理的,直到你編輯你的問題。下次嘗試更具體。 – Noseratio

回答

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; 
} 

如果你想顯示系統錯誤消息,使用該​​:

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); 
} 
+0

太棒了!非常感謝@Remy –

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

} 
相關問題