我写了一个系统服务,启动后需要读取注册表中的内容,需要读取的键是hkey_classes_root/http/shell/command中的键值,用普通程序能读出来,可在服务中就不行了,regqueryvalue返回值是234L。
是怎么回事?在网上找了一下,说是服务不能读取用户有关的注册表,因为服务不是以用户身份登陆的。可hkey_classes_root是local_machine中的一部分,跟用户应该没有关系的,怎么也不能直接读了?
请大虾们来讲讲吧。

解决方案 »

  1.   

    234L表示你给的缓冲区数据放不下
    这时一般RegQueryValue里面有个返回尺寸的参数告诉你需要多少字节空间
      

  2.   

    RegQueryValue在调用时,分两次,第一次让第三个参数为NULL,此时,第四个参数中为所需的大小,然后再用这个大小再调用一次即可
      

  3.   

    // #include   "stdafx.h"   
    #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,应该不会是数组大小的问题啊。
      

  4.   

    定义TCHAR   szKey[MAX_PATH]={0}; 
    用char szKey[2000]={0}; 结果也是一样的
      

  5.   

    你注册表读部分是正确的,原因是服务一般是不能和用户交互的,也就是说printf部分不行.
      

  6.   

    LONG RegQueryValue(
      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的值重新分配缓冲区。
      

  7.   

    我在2楼都跟你说过了。
    unsigned long subkey_len;未初始化,改成
    unsigned long subkey_len = sizeof(szKey);
    你在应用程序中调试时,VC把未初始化的变量初始化成0xcccccccc所以才会成功。
      

  8.   


    unsigned long subkey_len = MAX_PATH;lRet = RegQueryValueEx(hKey,NULL,0,NULL,(unsigned char *)szKey,&subkey_len);
      

  9.   

    多谢各位大侠,小弟受教了。
    确实应该是unsigned long subkey_len = MAX_PATH; 多谢了。