VC 设置环境变量

   //unicode编码下

       HKEY hregkey;
   DWORD dwReturnValue = 0;
   CString strEnvironmentPath(_T("")); //环境变量值

   TCHAR chsys[MAX_PATH] = {0};
   CString sSysCh;
   GetSystemDirectory( chsys , sizeof(chsys) ); //获取系统盘盘符
   sSysCh.Format( _T("%s") , chsys );
   CString charSysCh = _T("");
   charSysCh.Format(_T("%c"),sSysCh.GetAt(0));
   sSysCh = charSysCh + _T(":\\windows\\system32;") ;//设置system32环境变量参数
   long res = RegOpenKeyEx(HKEY_LOCAL_MACHINE, 
      _T("System\\CurrentControlSet\\Control\\Session Manager\\Environment"), 
      0, KEY_ALL_ACCESS, &hregkey); //打开注册表环境变量
   if(res == 0)
   {
     LPBYTE lpa = new BYTE[500];
      DWORD dwAidSize=500;
      DWORD type=REG_SZ;
      if(ERROR_SUCCESS == ::RegQueryValueEx(hregkey,_T("Path"),
         NULL,&type,lpa,&dwAidSize))
      {
         strEnvironmentPath = (LPTSTR)lpa;

       if (strEnvironmentPath.Find(sSysCh) !=  -1)
            return TRUE;
         strEnvironmentPath.Insert(0,sSysCh);   
         if (ERROR_SUCCESS ==::RegSetValueEx(hregkey,_T("Path"),
            0,REG_SZ,(LPBYTE)(LPCTSTR)strEnvironmentPath,
             strEnvironmentPath.GetLength()*2)
          )
       {
          SendMessageTimeout(HWND_BROADCAST, 
           WM_SETTINGCHANGE, 
           0, (LPARAM) _T("Environment"), 
           SMTO_ABORTIFHUNG, 
           5000,
           &dwReturnValue); //使修改的环境变量立即生效
          ::RegCloseKey(hregkey);
          return TRUE;
       }
       AfxMessageBox(strEnvironmentPath);
      }
      ::RegCloseKey(hregkey); 
   }

原文地址:https://www.cnblogs.com/pbreak/p/1745635.html