我写了一个系统服务,启动后需要读取注册表中的内容,需要读取的键是hkey_classes_root/http/shell/command中的键值,用普通程序能读出来,可在服务中就不行了,regqueryvalue返回值是234L。
是怎么回事?在网上找了一下,说是服务不能读取用户有关的注册表,因为服务不是以用户身份登陆的。可hkey_classes_root是local_machine中的一部分,跟用户应该没有关系的,怎么也不能直接读了?
请大虾们来讲讲吧。
是怎么回事?在网上找了一下,说是服务不能读取用户有关的注册表,因为服务不是以用户身份登陆的。可hkey_classes_root是local_machine中的一部分,跟用户应该没有关系的,怎么也不能直接读了?
请大虾们来讲讲吧。
这时一般RegQueryValue里面有个返回尺寸的参数告诉你需要多少字节空间
#include <stdio.h>
#include <windows.h> // 功能:列出指定键下的所有子键名
BOOL MyEnumKey()
{
char *szSubKey="http\\shell\\open\\command";
HKEY hKey;
LONG lRet=::RegOpenKeyEx(HKEY_CLASSES_ROOT, szSubKey, 0, KEY_READ, &hKey);
if(lRet!=ERROR_SUCCESS)
{
return FALSE;
}
TCHAR szKey[MAX_PATH]={0};
unsigned long subkey_len;
lRet = RegQueryValueEx(hKey,NULL,0,NULL,(unsigned char *)szKey,&subkey_len);
printf("OK:%s\n",szKey);
// 关闭注册表
::RegCloseKey(hKey);
return TRUE;
} int main(int argc, char* argv[])
{
MyEnumKey();
getchar();
return 0;
}就是这段代码,在一个普通的cpp中运行良好,可弄到我编写的系统服务中就不行了,RegQueryValueEx的返回值是234L,subkey_len是40,可我给的是MAX_PATH,应该不会是数组大小的问题啊。
用char szKey[2000]={0}; 结果也是一样的
HKEY hKey, // handle to key to query
LPCTSTR lpSubKey,
// name of subkey to query
LPTSTR lpValue, // buffer for returned string
PLONG lpcbValue // receives size of returned string
);
lpValue
Pointer to a buffer that receives the null-terminated string associated with the default value of the specified key.
If lpValue is NULL, and lpcbValue is non-NULL, the function returns ERROR_SUCCESS, and stores the size of the data, in bytes, in the variable pointed to by lpcbValue. This lets an application determine the best way to allocate a buffer for the value's data.
其中lpValue用于保存返回值,lpcbValue传入的是lpValue缓冲区大小,若lpValue缓冲区长度小于
所实际返回值需要的长度,函数返回ERROR_MORE_DATA,此时lpcbValue里面保存的是实际需要的长度。出现这种情况应该按照lpcbValue的值重新分配缓冲区。
unsigned long subkey_len;未初始化,改成
unsigned long subkey_len = sizeof(szKey);
你在应用程序中调试时,VC把未初始化的变量初始化成0xcccccccc所以才会成功。
unsigned long subkey_len = MAX_PATH;lRet = RegQueryValueEx(hKey,NULL,0,NULL,(unsigned char *)szKey,&subkey_len);
确实应该是unsigned long subkey_len = MAX_PATH; 多谢了。