从C ++代码设置当前用户环境变量对其他进程(如cmds)可见 [英] Set current user environment variable from c++ code visible to other process like cmds

查看:65
本文介绍了从C ++代码设置当前用户环境变量对其他进程(如cmds)可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为当前用户设置一个本地环境变量,它应该对其他进程(如新的命令提示符)可见.我需要用于Windows.我尝试了诸如putenv之类的选项,并通过C ++代码编辑了注册表,但是新的cmd提示符下看到的是旧值.首先,我需要编辑PATH变量以及一些自定义环境变量.如果我能得到一个有效的示例代码,将不胜感激.

I need to set a local environment variable for current user and it shoukd be visible to other processes like a new command prompt. I need it for windows. I have tried options like putenv and editing the registry from C++ code but the new cmd prompt see the old values. Primarily i need to edit PATH variable along with few custom env variables. Will appreciate if i can get a working sample code.

请注意,环境变量需要在程序执行后继续存在.

Please note that the environment variable need to persist past program execution.

我的要求是Windows.我什至尝试从C ++代码运行setx,它工作正常,但对于PATH变量,它将其缩减为1024个字符,并且我丢失了更新.有解决方法吗?

My requirement is for windows. I even tried running setx from C++ code and it works fine but for PATH variable it trims it down to 1024 character and i lose the update. Is there a workaround to this?

如果我的措辞对要求感到困惑.我需要与使用setx完全相同的行为.预先感谢.

IF my wording looks confusing about the requirement. I need exactly same behavior as if i am using setx. Thanks in advance.

推荐答案

如果从进程中启动Cmd.exe,则可以控制其环境.环境变量是从父进程继承的.当您调用 CreateProcess 时,它们也可以被覆盖.

If you start Cmd.exe from your process you can control its environment. The environment variables are inherited from the parent process. They can also be overridden when you call CreateProcess.

如果您在注册表中更改用户/系统环境配置( HKCU \ Environment / HKLM \ SYSTEM \ CurrentControlSet \ Control \ Session Manager \ Environment )并注销/reboot,那么第一个进程将使用这些新的默认值.

If you change the users/system environment configuration in the registry(HKCU\Environment/HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment) and log off/reboot then the first process will use these new defaults.

如果更新注册表,则可以通过广播

If you update the registry you can tell other applications to refresh their environments without logging off by broadcasting a message:

BroadcastSystemMessage(0, 0, WM_SETTINGCHANGE, 0, (LPARAM)TEXT("Environment")); 

实际上,只有Explorer.exe会对此消息作出反应,但这足以影响从任务栏/开始菜单启动的新应用程序.

In reality it is only Explorer.exe that reacts to this message but that is enough to affect new applications started from the taskbar/start menu.

这篇关于从C ++代码设置当前用户环境变量对其他进程(如cmds)可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆