使用 cpp 向注册表添加值的问题

Problem with add value to registry with cpp

我正在尝试向注册表添加值,以便 运行 我的程序在系统启动时和在 Regedit 中执行后。 HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run

只是路径“C”的第一个字母

int start_with_os() {
    long result;
    HKEY hkey;

    result = RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software\Microsoft\Windows\CurrentVersion\Run"),
        0, KEY_READ | KEY_WRITE | KEY_QUERY_VALUE, &hkey);
    if (result != ERROR_SUCCESS) return 1;

    char* fpath = new char;
    GetModuleFileNameA(NULL, fpath, MAX_PATH);

    const size_t cSize = strlen(fpath) + 1;
    wchar_t* wc = new wchar_t[cSize];

    size_t outSize;
    mbstowcs_s(&outSize, wc, cSize, fpath, cSize-1);

    OutputDebugStringW(wc);

    result = RegSetValueEx(hkey,  _T("sysservice"), 0, REG_SZ, (BYTE*)wc, strlen((const char*)wc));
    if (result != ERROR_SUCCESS) return 1;

    RegCloseKey(hkey);
    return 0;
}

变量 wc 的输出是正确的路径。 C:\Users\Piotrek\source\repos\myprogram\Release\myprogram.exe

从你提供的代码来看,我猜你的项目使用的是Unicode字符集。

Microsoft documentation表示RegSetValueEx的最后一个参数是以字节为单位。

cbData

The size of the information pointed to by the lpData parameter, in bytes. If the data is of type REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ, cbData must include the size of the terminating null character or characters.

所以,改变

result = RegSetValueEx(hkey,  _T("sysservice"), 0, REG_SZ, (BYTE*)wc, strlen((const char*)wc));

result = RegSetValueEx(hkey,  _T("sysservice"), 0, REG_SZ, (BYTE*)wc, (_tcslen(wc) + 1) * sizeof(TCHAR));

应该可以。


编辑:感谢@john 的评论,char* fpath = new char; 也是一个错误。

考虑直接使用TCHAR fpath[MAX_PATH];。 而下面的代码也需要改成T字符串函数