【代码备忘录】VC设置您的计算机环境变量、注册表操作

欢迎增加C/C++ QQ组,无论你的工作。学生,只有具备c / vc / c++ 编程经验。就来吧!158427611 


【设置电脑环境变量】

设置电脑环境变量非常easy,由于window而言。环境变量都相应的存储在注冊表中,所以仅仅要写注冊表就能做到新增删除改动环境变量了。

So easy

环境变量在注冊表中的位置: HKEY_CURRENT_USER ->Environment


so 看代码:

bool createComputerPath()
    {
        if(createReg(HKEY_CURRENT_USER,L"Environment",L"PathName",L"PathValue"))
        {
            //DWORD dwRet=0;

            //SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, NULL, (LPARAM)"Environment", SMTO_NOTIMEOUTIFNOTHUNG, INFINITE, &dwRet);

            //SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE , NULL, (LPARAM)"Environment",SMTO_NORMAL, 1000, &dwRet);
            //SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE , NULL, (LPARAM)"Environment", SMTO_NOTIMEOUTIFNOTHUNG,1000, &dwRet);

            ::SendMessage(HWND_BROADCAST,WM_SETTINGCHANGE,0,(LPARAM)TEXT("Environment")); //因为新增环境仅仅会 没有马上生效,所以须要发送
			//WM_SETTINGCHANGE消息给全部窗体。刷新环境变量

		return true; 
		} 
	return false; 
 }
   


【新增注冊表项】

    bool createReg(HKEY table,LPCTSTR key,LPCTSTR item,LPCTSTR values)
    {
        HKEY hAppKey = NULL;
        HKEY hSoftKey = NULL;

        if (RegOpenKeyEx(table, key, 0, KEY_WRITE|KEY_READ,&hSoftKey) == ERROR_SUCCESS)
        {
            if(RegSetValueEx(hSoftKey,
                item,
                NULL,
                REG_SZ,
                (LPBYTE)values, 
                (lstrlen(values)+1) * sizeof(TCHAR)) == ERROR_SUCCESS)
            {
                if (hSoftKey != NULL)
                {
                    RegCloseKey(hSoftKey);
                }   

                if (hAppKey != NULL)
                {
                    RegCloseKey(hAppKey);
                }   

                return true;
            }
        }
        if (hSoftKey != NULL)
        {
            RegCloseKey(hSoftKey);
        }   

        if (hAppKey != NULL)
        {
            RegCloseKey(hAppKey);
        }   

        return false;
    }

【读取注冊表】

    std::string getInnoSetupPath()
    {
        //CString regPath = L"HKEY_CLASSES_ROOT\InnoSetupScriptFile\shell\open\command";
        HKEY hKEY;//定义有关的hKEY,在查询结束时要关闭

        LPCTSTR data_Set=L"InnoSetupScriptFile\\shell\\open\\command\\";
        if(::RegOpenKeyEx(HKEY_CLASSES_ROOT,data_Set,0,KEY_READ,&hKEY) != ERROR_SUCCESS)//假设无法打开hKEY,则中止程序的运行
        {
            return "";
        }

        TCHAR res[MAX_PATH];//=new BYTE[MAX_PATH];
        DWORD type_1=REG_SZ;//定义数据类型
        DWORD cbData_1=MAX_PATH;//定义数据长度
        if(RegQueryValueEx(hKEY,L"",NULL,&type_1,(LPBYTE)res,&cbData_1)!=ERROR_SUCCESS)
        {
            return "";
        }
        
        ::RegCloseKey(hKEY);
        return CStringConvert::CString2string(res);//CString转string
    }

欢迎增加C/C++ QQ群,不管你是否工作,学生。仅仅要有c / vc / c++ 编程经验,就来吧!

158427611 

版权声明:本文博客原创文章。博客,未经同意,不得转载。

你可能感兴趣的:(环境变量)