// regTest.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Windows.h> #include <iostream> /* 对于注册表,我们可以理解为(类比): 键对应于文件夹,键值对应于文件 */ VOID ErrorShow(DWORD dwErrorCode); VOID ErrorShow(DWORD dwErrorCode) { DWORD systemLoacle = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL); HLOCAL hlocal = NULL; BOOL bOk = ::FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER, NULL, dwErrorCode, systemLoacle, (PTSTR)&hlocal, 0, NULL); if (!bOk) { HMODULE hDll = ::LoadLibraryEx(_T("netmsg.dll"), NULL, DONT_RESOLVE_DLL_REFERENCES); if (hDll != NULL) { bOk = ::FormatMessage( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER, hDll, dwErrorCode, systemLoacle, (PTSTR)&hlocal, 0, NULL); ::FreeLibrary(hDll); } } if (bOk != FALSE && hlocal != NULL) { OutputDebugString((PTSTR)hlocal); ::LocalFree(hlocal); } else { OutputDebugString(_T("No text found for this error number")); } } int _tmain(int argc, _TCHAR* argv[]) { /* 需要打开的键,可以是: HKEY_CLASSES_ROOT HKEY_CURRENT_USER HKEY_LOCAL_MACHINE HKEY_USERS HKEY_CURRENT_CONFIG */ HKEY hKey = HKEY_CURRENT_USER; HKEY hRetKey; LONG lRet = ::RegOpenKeyEx(hKey, _T("Software"), 0, KEY_QUERY_VALUE, &hRetKey); if (lRet != ERROR_SUCCESS) { ErrorShow(lRet); std::cout << "error" << std::endl; } else { HKEY hKSG; DWORD dw; //Software//KSG /* 新创建的:REG_CREATED_NEW_KEY 已存在:REG_OPENED_EXISTING_KEY 这个函数会帮助我们建立中间的键 */ lRet = ::RegCreateKeyEx(hRetKey, _T("KSG//KIS"), 0, REG_NONE, REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKSG, &dw); if (dw == REG_CREATED_NEW_KEY) { std::cout << "new key" << std::endl; } else if (dw == REG_OPENED_EXISTING_KEY) { std::cout << "exist key" << std::endl; } if (lRet != ERROR_SUCCESS) { ErrorShow(lRet); std::cout << "error" << std::endl; } else { //设置键值 ::RegSetValueEx(hKSG, _T("Name"), 0, REG_SZ, (PBYTE)_T("Liyong"), (_tcslen(_T("Liyong")) + 1) * sizeof(TCHAR)); ::RegCloseKey(hKSG); std::cout << "success" << std::endl; } ::RegCloseKey(hRetKey); std::cout << "success" << std::endl; } //读取键值 /* HKEY hMyKey; ::RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software//KSG//KIS"), 0, KEY_QUERY_VALUE, &hMyKey); TCHAR szBuffer[MAX_PATH] = { 0 }; DWORD dwSize = MAX_PATH * sizeof(TCHAR); DWORD dwType; ::RegGetValue(hMyKey, NULL, _T("Name"), 0, &dwType, szBuffer, &dwSize); ::RegCloseKey(hMyKey); */ HKEY hMyKey; ::RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software//KSG//KIS"), 0, KEY_ALL_ACCESS, &hMyKey); ::RegDeleteValue(hMyKey, _T("Name")); ::RegCloseKey(hMyKey); ::RegOpenKeyEx(HKEY_CURRENT_USER, _T("Software//KSG//KIS"), 0, KEY_ALL_ACCESS, &hMyKey); //::RegDeleteKeyEx(hMyKey, NULL, NULL, 0); ::RegDeleteKey(hMyKey, NULL); ::RegCloseKey(hMyKey); return 0; }