吵吵   2011-06-13  阅读:2,485

在vc编程里面总是要用到注册表的几个函数,在一个程序中一般来说用的最多的是读写整数和读写字符串,用一个类来写可能方便点,但是也占资源,高频率的几个我就用成全局函数了,不敢私藏,拿出来共享下:
一下是代码包括:
int SetRegInt(LPCTSTR keyname,DWORD keyvalue);写入int
int GetRegInt(LPCTSTR keyname);读取int
int SetRegString(LPCTSTR keyname,char * keyvalue);写入字符串
int GetRegString(LPCTSTR keyname,char * keyvalue);得到字符
int DeleteRegKey(LPCTSTR keyname);删除子键


int SetRegInt(LPCTSTR keyname,DWORD keyvalue)
{

HKEY hKey;
LPCTSTR lpRun = "Software\\chaochao"; //我这里这个程序的注册表项就放在chaochao下了自己可以改
DWORD lRet=::RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpRun, 0, KEY_ALL_ACCESS , &hKey);
if(lRet == ERROR_SUCCESS)//打开注册表成功
{

lRet = RegSetValueEx(hKey, keyname, 0,REG_DWORD, (CONST BYTE*)&keyvalue,sizeof(DWORD));

//关闭注册表
RegCloseKey(hKey);
if(lRet == ERROR_SUCCESS)
{
return 0;//写入成功

}
else
{
return -1;//写入失败

}

}
else
{
return -1;//打开注册表失败
}
}

int GetRegInt(LPCTSTR keyname)
{

HKEY hKey;
LPCTSTR lpRun = "Software\\chaochao";
DWORD keyvalue;
DWORD lRet=::RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpRun, 0, KEY_ALL_ACCESS , &hKey);
if(lRet == ERROR_SUCCESS)
{
DWORD Type = REG_DWORD;
DWORD Size = sizeof(DWORD);

lRet =::RegQueryValueEx(hKey, keyname, 0,&Type, (BYTE*)&keyvalue,&Size);

//关闭注册表
RegCloseKey(hKey);
if(lRet == ERROR_SUCCESS) //读取成功
{
return keyvalue;

}
else
{
return -1;//读取失败www.chaochaoblog.com

}

}
else
{
return -1;//打开键值失败
}
}
int SetRegString(LPCTSTR keyname,char * keyvalue)
{

HKEY hKey;
LPCTSTR lpRun = "Software\\chaochao";
DWORD lRet=::RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpRun, 0, KEY_ALL_ACCESS , &hKey);
if(lRet == ERROR_SUCCESS)
{

lRet = RegSetValueEx(hKey, keyname, 0,REG_SZ, (BYTE*)keyvalue,strlen(keyvalue));

//关闭注册表
RegCloseKey(hKey);
if(lRet == ERROR_SUCCESS)
{
return 0;

}
else
{
return -1;

}

}
else
{
return -1;
}

}

int GetRegString(LPCTSTR keyname,char * keyvalue)
{
HKEY hKey;
LPCTSTR lpRun = "Software\\chaochao";
DWORD lRet=::RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpRun, 0, KEY_ALL_ACCESS , &hKey);
if(lRet == ERROR_SUCCESS)
{
DWORD Type = REG_SZ;
DWORD Size = strlen(keyvalue);
lRet = RegQueryValueEx(hKey, keyname, 0,&Type,(unsigned char *) keyvalue,&Size);

//关闭注册表
RegCloseKey(hKey);
if(lRet == ERROR_SUCCESS)
{
return 0;

}
else
{
return -1;

}

}
else
{
return -1;
}
}

int DeleteRegKey(LPCTSTR keyname)
{

HKEY hKey;

LPCTSTR lpRun = "Software\\chaochao";

DWORD lRet=::RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpRun, 0, KEY_ALL_ACCESS , &hKey);
if(lRet == ERROR_SUCCESS)
{

lRet = RegDeleteValue(hKey, keyname);

//关闭注册表
RegCloseKey(hKey);
if(lRet == ERROR_SUCCESS)
{
return 0;

}
else
{
return -1;

}

}
else
{
return -1;
}

}

注意,我给出的几个函数在注册表中都是software/chaochao下的,自己的程序自己改!

吵吵微信朋友圈,请付款实名加入:

吵吵 吵吵

发表评论

电子邮件地址不会被公开。 必填项已用*标注