注册表修改( RegCreateKeyEx , RegSetValueEx )

来源:互联网 发布:平价眼影推荐 知乎 编辑:程序博客网 时间:2024/04/30 05:10
今天的一个程序需要在注册表中添加开机启动,于是想到用程序实现,Google & MSDN 了一下,其实还是很容易实现。

比如我需要在开机的时候,让系统自动运行 C:/Program Files/UDP Clt.exe。步骤如下:

1. #include <windows.h>

2. 调用 platform SDK: ::RegCreateKeyEx() 创建/打开注册表的键值, 查阅MSDN如下:

 LONG   RegCreateKeyEx(   
      HKEY   hKey,                                   //   handle   to   an   open   key   
      LPCTSTR   lpSubKey,                   //   address   of   subkey   name   
      DWORD   Reserved,                     //   reserved   
      LPTSTR   lpClass,                         //   address   of   class   string   
      DWORD   dwOptions,                    //   special   options   flag   
      REGSAM   samDesired,                //   desired   security   access   
      LPSECURITY_ATTRIBUTES   lpSecurityAttributes,   
                                                                 //   address   of   key   security   structure   
      PHKEY   phkResult,                       //   address   of   buffer   for   opened   handle   
      LPDWORD   lpdwDisposition      //   address   of   disposition   value   buffer   
  );   

RegCreateKeyEx() 在键值存在的情况下将打开该键值,如不存在将创建一个键值。

3. 调用 ::RegSetValueEx(),修改键值 
LONG RegSetValueEx(  HKEY hKey,  LPCTSTR lpValueName,  DWORD Reserved,  DWORD dwType,  const BYTE* lpData,  DWORD cbData);
4. 调用 ::RegCloseKey() 关闭该键值

程序实现如下:
  1. #include <windows.h>
  2. #include <stdio.h>
  3. #define _T(a)   a
  4. int main()
  5. {
  6.     HKEY    hKEY;   
  7.     LPCTSTR path;
  8.     long    ret;
  9.    
  10.     //  specific subkey
  11.     path = _T("SOFTWARE//Microsoft//Windows//CurrentVersion//Run");  
  12.     //  create key, if already exit open it
  13.     ret = ::RegCreateKeyEx(HKEY_LOCAL_MACHINE, path, NULL, NULL, 
  14.         REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKEY, NULL);
  15.     if(ret != ERROR_SUCCESS)
  16.     {   
  17.         //  create / open failed
  18.         printf("Error ! RegCreateKeyEx() failed!/n");
  19.         exit(0);   
  20.     }   
  21.     
  22.     unsigned char   tmp[256] = "/0";   
  23.     DWORD           size;   
  24.     //  specific key value
  25.     sprintf((char *)tmp, "C://program files//UDP Clt.exe");
  26.     size = strlen((char *)tmp) + 1;
  27.     //  set value
  28.     ret = ::RegSetValueEx(hKEY,"UDP Clt",NULL,REG_SZ,tmp,size);   
  29.     if(ret != ERROR_SUCCESS)   
  30.     {     
  31.         //  set failed
  32.         printf("Error ! RegSetValueEx() failed!/n");
  33.         exit (0);   
  34.     }  
  35.   
  36.     //  close key
  37.     ::RegCloseKey(hKEY);  
  38.   
  39.     return 0;
  40. }

原创粉丝点击