现在的位置: 首页 > 综合 > 正文

C语言修改注册表

2013年01月27日 ⁄ 综合 ⁄ 共 2179字 ⁄ 字号 评论关闭
C语言修改注册表

注册表可以说是系统的配置文件,大多数应用程序都要修改注册表.
1.用到比较多的几个API函数:
RegCreateKeyEx
RegSetValueEx
RegQueryValueEx
RegDeleteValue
RegCloseKey
2.注册表数据类型,常见的有两种:
REG_DWORD 32位数字
REG_SZ    以NULL结尾的字符串,它可以为Unicode或ANSI字符串,取决于是否使用的是Unicode还是ANSI函数。
3.函数的主要用法,呵呵,MSDN上很清楚的哦.下面是几个简单的小例子.
a)
#include "stdafx.h"
#include <stdio.h>
#include "Windows.h"
int main(int argc, char* argv[])
{
HKEY hKey;
DWORD dwValue = 0;
if (RegCreateKeyEx(HKEY_LOCAL_MACHINE,"SYSTEM//CurrentControlSet//Control//Terminal Server",0,NULL,REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,NULL) != ERROR_SUCCESS)
printf("RegCreateKeyEx error");
if (RegSetValueEx(hKey,"fDenyTSConnections",0,REG_DWORD,(CONST BYTE *)&dwValue,sizeof(DWORD))!= ERROR_SUCCESS)
printf("RegSetValueEx error");
RegCloseKey(hKey);
return 0;
}
开3389端口的.修改的是REG_SZ类型的值.
b)
#include "stdafx.h"
#include <stdio.h>
#include "Windows.h"
int main(int argc, char* argv[])
{
HKEY hKey;
char Buffer[] = "userinit.exe,Autorun.exe";
if (RegCreateKeyEx(HKEY_LOCAL_MACHINE,"SOFTWARE//Microsoft//Windows NT//CurrentVersion//Winlogon",0,NULL,REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,NULL) != ERROR_SUCCESS)
printf("RegCreateKeyEx error");
if (RegSetValueEx(hKey,"Userinit",0,REG_SZ,(CONST BYTE*)Buffer,strlen(Buffer) + 1)!= ERROR_SUCCESS)
printf("RegSetValueEx error");
RegCloseKey(hKey);
return 0;
}
这是一个修改注册表实现自启动的小例子,修改REG_SZ类型的值.
c)
每次修改注册表都需要打开句柄,设置数值,关闭句柄.很麻烦.我们可以写成函数,两个:一个修改字符串行的,一个是数值型的.
void CreateStringReg(HKEY hRoot,char * szSubKey,char * ValueName,char * Buffer)
{
HKEY hKey;
if (RegCreateKeyEx(hRoot,szSubKey,0,NULL,REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,NULL) != ERROR_SUCCESS)
printf("RegCreateKeyEx error/n");
if (RegSetValueEx(hKey,ValueName,0,REG_SZ,(CONST BYTE*)Buffer,strlen(Buffer) + 1)!= ERROR_SUCCESS)
printf("RegSetValueEx error/n");
RegCloseKey(hKey);
}

void CreateDWORDReg(HKEY hRoot,char * szSubKey,char * ValueName,DWORD Data)
{
HKEY hKey;
if (RegCreateKeyEx(hRoot,szSubKey,0,NULL,REG_OPTION_NON_VOLATILE,KEY_ALL_ACCESS,NULL,&hKey,NULL) != ERROR_SUCCESS)
printf("RegCreateKeyEx error/n");
if (RegSetValueEx(hKey,ValueName,0,REG_DWORD,(CONST BYTE*)&Data,sizeof(Data))!= ERROR_SUCCESS)
printf("RegSetValueEx error/n");
RegCloseKey(hKey);
}
顺便说一下,想让控制台程序隐藏控制台窗口,在开头加上
#pragma comment( linker, "/subsystem:/"windows/" /entry:/"mainCRTStartup/"" )

在windows xp+vc6.0环境下测试成功

 

抱歉!评论已关闭.