今天刚学了对注册表的读写操作。在这里总结一下。
主要用到的函数有:
LONG WINAPI RegCreateKey( //Creates the specified registry key. If the key already exists in the registry, the function opens it. __in HKEY hKey, //创建一个指定的注册表项,如果这个表项已经存在,则打开它 __in_opt LPCTSTR lpSubKey, __out PHKEY phkResult ); LONG WINAPI RegSetValue( //Sets the data for the default or unnamed value of a specified registry key. The data must be a text string. __in HKEY hKey, //设置一个指定的默认的或者是未命名的注册表项的值。这个值必须是文本串,也就是说只能写入文本类型的值 __in_opt LPCTSTR lpSubKey, __in DWORD dwType, __in_opt LPCTSTR lpData, __in DWORD cbData ); LONG WINAPI RegQueryValue( //Retrieves the data associated with the default or unnamed value of a specified registry __in HKEY hKey, // The data must be a null-terminated string __in_opt LPCTSTR lpSubKey, //获得一个指定的默认的或者是未命名的注册表项的值,这个值必须是文本串 __out_opt LPTSTR lpValue, //与RegSetValue相对应 __inout_opt PLONG lpcbValue );
实现:
1.首先调用RegCreateKey()函数,创建指定的注册表项,代码如下:HKEY hKey; RegCreateKey(HKEY_LOCAL_MACHINE, "Software\\Lin\\admin", &hKey);
参数说明:第一个参数hKey的取值可以是下面的这些,这些值在注册表中都可看到,如下:
- HKEY_CLASSES_ROOT
- HKEY_CURRENT_CONFIG
- HKEY_CURRENT_USER
- HKEY_LOCAL_MACHINE
- HKEY_USERS
第二个参数可以理解为在上面那些文件夹的路径,代码中"Software\\Lin\\admin",如果没有找到相应的文件夹,则新建。
第三个参数是个接收句柄,得到的句柄在下面要用到。
2.然后调用RegSetValue()函数,写入想写入的字符串值。(完成了数据的写入)代码如下:RegSetValue(hKey, "hello", REG_SZ, "hi", strlen("hi"));