c++ 注册表操作(打开,添加子项)

 本文思路:c++ 打开注册表中的某一项GameManagerServer,在其下面添加子项Parameters,并为Parameters新建子项以及赋值。

// Temp.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include 
#include 
#include 

int _tmain(int argc, _TCHAR* argv[])
{
	//1.执行批处理命令
	//将exe创建为一个服务(方法二)
	system("instsrv GameManagerServer C:\\Windows\\System32\\srvany.exe");

	HKEY hKey;
	HKEY hKeyPara;
	HKEY hTempKey;
	LPCTSTR SubKey = _T("SYSTEM\\CurrentControlSet\\Services\\GameManagerServer");
	LPCTSTR SubKeyPara = _T("SYSTEM\\CurrentControlSet\\Services\\GameManagerServer\\Parameters");
	CString m_name = "D:\\server\\GameManagerServer\\GameManageSvr.exe";
	CString m_nameDirectory = "D:\\server\\GameManagerServer\\";
	LPBYTE m_name_Set = (LPBYTE)(LPCTSTR)(m_name);//定义x轴名称
	LPBYTE m_name_SetDirectory = (LPBYTE)(LPCTSTR)(m_nameDirectory);//定义x轴名称
	DWORD length = m_name.GetLength() + 50;//定义数据长度,定义长点,否则字段会被截取

	//2.编辑注册表
	//打开上一步创建的服务的注册表项GameManagerServer,添加项Parameters
	if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE, SubKey, 0, KEY_ALL_ACCESS, &hKey))//打开注册表项
	{
		printf("打开GameManagerServer注册表成功\r\n");
		if (ERROR_SUCCESS == RegCreateKey(hKey, _T("Parameters"), &hTempKey))//添加项Parameters
		{
			printf("创建Parameters成功\r\n");
		}
		else
		{
			MessageBox(NULL, _T("创建Parameters错误!"), _T("错误"), NULL);

		}
	}
	else
	{
		MessageBox(NULL, _T("打开GameManagerServer注册表错误!"), _T("错误"), NULL);
	}
	::RegCloseKey(hKey);

	//打开注册表项Parameters,添加子键Application、AppDirectory、AppParameters并赋值
	if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, SubKeyPara, 0, KEY_ALL_ACCESS, &hKeyPara) == ERROR_SUCCESS)//打开注册表项Parameters
	{
		//添加子键Application
		if (ERROR_SUCCESS != ::RegSetValueEx(hKeyPara, _T("Application"), 0, REG_SZ, m_name_Set, length))
		{
			MessageBox(NULL, _T("添加子键Application错误!"), _T("错误"), NULL);
			::RegCloseKey(hKeyPara);
		}
		else
		{
			//添加子键AppDirectory
			if (ERROR_SUCCESS != ::RegSetValueEx(hKeyPara, _T("AppDirectory"), 0, REG_SZ, m_name_SetDirectory, length))
			{
				MessageBox(NULL, _T("添加子键AppDirectory错误!"), _T("错误"), NULL);
				::RegCloseKey(hKeyPara);
			}
			else
			{
				//添加子键AppParameters
				if (ERROR_SUCCESS != ::RegSetValueEx(hKeyPara, _T("AppParameters"), 0, REG_SZ, NULL, NULL))
				{
					MessageBox(NULL, _T("添加子键AppParameters错误!"), _T("错误"), NULL);
					::RegCloseKey(hKeyPara);
				}
				else
				{
					printf("GameManagerServer添加系统服务成功\r\n");
					MessageBox(NULL, _T("GameManagerServer添加系统服务成功!"), _T("提示"), NULL);
					::RegCloseKey(hKeyPara);
				}
			}
		}
	}
	else
	{
		MessageBox(NULL, _T("打开注册表项Parameters错误!"), _T("错误"), NULL);
	}

	return 0;
}
运行结果:

c++ 注册表操作(打开,添加子项)_第1张图片



你可能感兴趣的:(C/C++)