RegOpenKeyEx 返回 ERROR_SUCCESS 但它不应该返回(Windows 7)
我遇到了一个关于RegOpenKeyEx的问题,代码:
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
#pragma comment (lib, "Advapi32.lib")
int main () {
TCHAR *keyName = _T("SOFTWARE\\foobar2000\\capabilities");
HKEY key = NULL;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, KEY_ALL_ACCESS, &key) != ERROR_SUCCESS) {
printf("open key failed!\n");
return -1;
} else {
printf("open key success!\n");
}
TCHAR *value = _T("123");
if (RegSetValueEx(key, _T("xxx"), 0, REG_SZ,
(const BYTE *)value, sizeof(TCHAR) * (_tcslen(value) + 1)) != ERROR_SUCCESS) {
printf("set value failed!\n");
}
RegCloseKey(key);
return 0;
}
将代码保存在如reg.cpp中,在命令模式下:
cl reg.cpp
就得到了reg.exe,运行它:
D:\tmp>reg.exe
open关键成功!
但该值尚未写入注册表。
另一个奇怪的事情是,如果我使用 Visual Studio 创建一个 CLI 项目,并将代码粘贴到 main() 中,RegOpenKeyEx() 将返回 false。
平台为windows 7,启用UAC。
I've got a problem about RegOpenKeyEx, the code:
#include <tchar.h>
#include <stdio.h>
#include <windows.h>
#pragma comment (lib, "Advapi32.lib")
int main () {
TCHAR *keyName = _T("SOFTWARE\\foobar2000\\capabilities");
HKEY key = NULL;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, KEY_ALL_ACCESS, &key) != ERROR_SUCCESS) {
printf("open key failed!\n");
return -1;
} else {
printf("open key success!\n");
}
TCHAR *value = _T("123");
if (RegSetValueEx(key, _T("xxx"), 0, REG_SZ,
(const BYTE *)value, sizeof(TCHAR) * (_tcslen(value) + 1)) != ERROR_SUCCESS) {
printf("set value failed!\n");
}
RegCloseKey(key);
return 0;
}
Save the code in such as reg.cpp, and in command mode:
cl reg.cpp
and I got reg.exe, run it:
D:\tmp>reg.exe
open key success!
But the value hasn't been written in the registry.
Another strange thing is that if I use the visual studio to create a CLI project, and paste the code into main(), the RegOpenKeyEx() will return false.
The platform is windows 7, and UAC is enabled.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
听起来您正在遇到虚拟化问题。如果应用没有清单,当您尝试写入 HKLM\Software 时,它实际上会写入
HKEY_USERS\_Classes\VirtualStore\Machine\Software
。为了防止这种情况,您可以提升运行该应用程序。您可能想要添加一个清单,强制它每次都以提升的权限运行。或者,停止写入 HKLM 并改用 HKCU。至于 C++/CLI 部分,我的猜测是您会获得该部分的 asInvoker 清单,该清单会抑制虚拟化并导致尝试访问 HKLM 失败。
Sounds like you're running into virtualization. IF the app has no manifest, when you try to write to HKLM\Software it actually writes to
HKEY_USERS\<User SID>_Classes\VirtualStore\Machine\Software
. To prevent this, you can run the app elevated. You might want to add a manifest forcing it to run elevated every time. Alternatively, stop writing to HKLM and use HKCU instead.As for the C++/CLI part, my guess would be you are given an asInvoker manifest for that one, which suppresses virtualization and results in the attempt to get to HKLM failing.