通过注册表方式修改系统换变量
#include <windows.h>
#include <iostream>
#include <thread>
int main() {
HKEY hKey;
const char* en_name = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
const char* key_name = "third";
std::string third_value = "D:\\third_dll";
const char* path_name = "Path";
DWORD type = REG_SZ;
DWORD size = strlen(third_value.c_str()) + 1;
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, en_name, 0, KEY_WRITE, &hKey) != ERROR_SUCCESS) {
std::cout << "Failed to open registry key." << std::endl;
return 1;
}
if (RegSetValueExA(hKey, key_name, 0, type, (LPBYTE)third_value.c_str(), size) != ERROR_SUCCESS) {
std::cout << "Failed to set registry value." << std::endl;
return 1;
}
std::string path_value = getenv("Path");
path_value = path_value + ";%" + key_name + "%";
DWORD path_size = strlen(path_value.c_str()) + 1;
if (RegSetValueExA(hKey, path_name, 0, type, (LPBYTE)path_value.c_str(), path_size) != ERROR_SUCCESS) {
std::cout << "Failed to read path value." << std::endl;
return 1;
}
std::cout << "Path: " << path_value << std::endl;
if (RegCloseKey(hKey) != ERROR_SUCCESS) {
std::cout << "Failed to close registry key." << std::endl;
return 1;
}
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Environment variable set successfully." << std::endl;
return 0;
}
对exe进行环境变量修改
#include <windows.h>
#include <iostream>
#define BUFSIZE 4096
int main(int argc, char *argv[])
{
LPTSTR path_value;
LPTSTR newValue[MAX_PATH];
path_value = (LPTSTR)malloc(BUFSIZE * sizeof(TCHAR));
const char* key_name = "third";
std::string third_value = "D:\\third_dll";
std::string proc_name = "project.exe";
DWORD dwRet = GetEnvironmentVariableW(L"Path", path_value, BUFSIZE);
std::string new_path = ConvertLPCTSTRToString(path_value) + std::string("%") + key_name + std::string("%");
SetEnvironmentVariable(L"Path", ConvertToLPWSTR(new_path));
dwRet = GetEnvironmentVariable(L"Path", path_value, BUFSIZE);
}
通过批处理方式修改
std::string batch_value = std::string("D:\\") + "setting.bat";
std::string value_1 = std::string("D:\\") + "third_dll";
value_1 = "setx Third_Dll \"" + value_1 + "\" -m";
std::string value_2 = "setx Path \"" + std::string("%%Third_Dll%%;%Path%") + "\" /m";
batchFile.open(batch_value);
if (batchFile.is_open()) {
batchFile << "@echo on" << std::endl;
batchFile << value_1 << std::endl;
batchFile << value_2 << std::endl;
batchFile << "pause" << std::endl;
batchFile.close();
}
else {
std::cout << "Failed to create batch file." << std::endl;
}
system(batch_value.c_str());
cmd黑框隐藏、显示
#include <windows.h>
int main() {
FreeConsole();
AllocConsole();
getchar();
return 0;
}