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

0 votes
asked Dec 2, 2010 by profk

We have just discovered that code that calls the Win32 SetDateTime function needs to run in elevated mode in Windows 7, i.e. 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?

3 Answers

0 votes
answered Dec 2, 2010 by ran

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.

0 votes
answered Dec 2, 2010 by hans-passant

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.

0 votes
answered Dec 2, 2010 by scott-wisniewski

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.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...