【发布时间】:2017-02-20 17:38:35
【问题描述】:
我目前正在尝试从“Software\Microsoft\Windows\CurrentVersion\Run”中删除一个子项。问题是尽管尝试了所有可能的解决方案,但我的错误代码是独一无二的,唯一的问题尚未得到解答:how to remove program from startup list using c++。我在 Windows x64 10 上使用 Visual Studio,程序是 Win32 应用程序。
创建密钥:
BOOL registerForLocalStartup(PCWSTR regName, PCWSTR pathToExe, PCWSTR args)
{
HKEY hKey = NULL;
LONG lResult = 0;
BOOL fSuccess = TRUE;
DWORD dwSize;
const size_t count = MAX_PATH * 2;
wchar_t szValue[count] = {};
wcscpy_s(szValue, count, L"\"");
wcscat_s(szValue, count, pathToExe);
wcscat_s(szValue, count, L"\" ");
if (args != NULL)
{
// caller should make sure "args" is quoted if any single argument has a space
// e.g. (L"-name \"Mark Voidale\"");
wcscat_s(szValue, count, args);
}
// For admin HKEY_LOCAL_MACHINE
lResult = RegCreateKeyEx(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, NULL, 0, (KEY_WRITE | KEY_READ), NULL, &hKey, NULL);
fSuccess = (lResult == 0);
if (fSuccess)
{
dwSize = (wcslen(szValue) + 1) * 2;
lResult = RegSetValueExW(hKey, regName, 0, REG_SZ, (BYTE*)szValue, dwSize);
fSuccess = (lResult == 0);
}
if (hKey != NULL)
{
RegCloseKey(hKey);
hKey = NULL;
}
return fSuccess;
}
这是我的代码:
bool DeleteValueKey(HKEY hKeyRoot, std::wstring Subkey, std::wstring ValueKey)
{
HKEY hKey = NULL;
bool bReturn = false;
long result = RegOpenKeyEx(hKeyRoot, Subkey.c_str(), 0, KEY_READ | KEY_WRITE | KEY_WOW64_32KEY, &hKey);
wcout << "Result of RegOpenKeyEx: " << result << endl;
if (result == ERROR_SUCCESS)
{
long result2 = RegDeleteKeyEx(hKey, ValueKey.c_str(), KEY_WOW64_32KEY, 0);
wcout << "Result of RegDeleteKeyEx: " << result2 << endl;
if (result2 == ERROR_SUCCESS)
{
bReturn = true;
}
}
if (hKey != NULL) { RegCloseKey(hKey); }
return bReturn;
}
这就是我试图调用的:
bool result = DeleteValueKey(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Run", L"test1");
if (result)
{
wcout << "SUCCESS" << endl;
}
else
{
wcout << "FAILURE: "<< GetLastError() << endl;
}*/
输出:
Result of RegOpenKeyEx: 0
Result of RegDeleteKeyEx: 2
FAILURE: 0
有人有想法吗?无法解决如此明显的问题,我快疯了……
【问题讨论】:
-
为什么不检查注册表函数的返回值以查看实际错误是什么 - 您的代码丢弃了这些重要信息。
-
您的程序是 32 位还是 64 位?你的 Windows 是 32 位还是 64 位?你得到什么错误代码?
::GetLastError()返回什么? -
我使用 Windows x64,我的应用程序是 x32。我得到的错误代码是 0。
-
"RegDeleteKeyEx 的结果:2" 未找到 2 此外,您只需将 KEY_WOW64_32KEY 传递给删除。因此打开和删除看到注册表的不同视图
-
我正在检查自动运行的关键是在那里!
标签: c++ windows visual-studio key registry