How do I check if my program is running under admin privileges via C++? [duplicate]

不打扰是莪最后的温柔 提交于 2019-12-08 10:08:14

问题


How do I check if my C++ program is running with admin privileges?

I did it in this manner for batch

set fold=%random%

mkdir "C:\Windows\%fold%"

if errorlevel 1 (

goto Tag1

)

goto Tag2

But I cannot use the same thing for C++ because I do not know how to transfer value of %random% that is variable 1 to variable 2 that is %fold% and also, I do not know if there is error level for C++.

Can anyone help me in this case or is there any way to check if my program is running with admin privileges?


回答1:


You can use the OpenProcessToken / GetTokenInformation pair: https://stackoverflow.com/a/8196291/3235496

An alternative is the AccessCheck function.

Last the IsUserAnAdmin function: it's simple but deprecated (available from Windows XP/Windows Server 2003).

Anyway why are you checking? Trying could be a good strategy: if it works, you have sufficient rights (possibly a subset of Admin rights).

PS

Just out of curiosity... the C++ translation of your batch file should be based on the CreateDirectory function. If it fails check the extended error information via GetLastError (return code ERROR_ACCESS_DENIED). But, as David Heffernan says, spraying folders into the system directories isn't a great idea.




回答2:


You find the answer in the MSDN:

https://support.microsoft.com/kb/118626

Also your application should have a manifest.



来源:https://stackoverflow.com/questions/26230294/how-do-i-check-if-my-program-is-running-under-admin-privileges-via-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!