简体   繁体   中英

How to call a Win32 API with elevated priviledges on Windows 7

We have just discovered that code that calls the Win32 SetDateTime function needs to run in elevated mode in Windows 7, ie even when logged in as an administrator, one still has to choose to run the Set Date code as Administrator for the call to change the date.

Is there anything I can do in code to always call this function under elevated privileges?

You can use the ShellExecute API call to launch an executable with elevated privileges.

However, if UAC (user access control) is enabled on the machine, the user will still get the UAC prompt asking for permissions to run elevated.

So I don't think you can avoid the prompt for elevation permission, but at least your user doesn't have to manually run the program as an admin.

Please let me know if you need help in how to launch an executable as an admin.

This is just not how security works. Changing the clock is a very intrusive operation, it has a very large number of side effects. There is no mechanism in Windows, or any other operating system for that matter, where you could start a process with limited privileges and then just arbitrarily bypass these limitations and suddenly gain administrator rights. There wouldn't be any point whatsoever to running programs with limited privileges if that was possible.

If you want to do something like this then you'll have to run your program with elevated rights. On Vista and Win7 that requires you to run as a service or a scheduled task. Which require an administrator to get installed. UAC provides a way gain admin rights for regular programs, you have to include a manifest in your program so the user is notified about your privilege elevation. Google 'requireadministrator', take the first hit.

Like others have said, you need to spawn a new process to get elevated permissions, which will result in a UAC dialog.

If this is something you need to run unattended you could try running as a service. That would give you the elevated context you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM