سؤال

We ran into problems with code that already worked to elevate the rights of a helper process that installs a new printer.

I found this answer here, which nearly matches our code: Windows 7 and Vista UAC - Programmatically requesting elevation in C#

The only difference is that we had set ShellExecute to false. This caused a Win32Exception that the process requires elevated rights. Use ShellExecute solved this.

My question is: why? Most likely there is an answer to that that makes sense and would really to understand what happens so I will know next time something similar is required.

Many thanks in advance for all hints!

هل كانت مفيدة؟

المحلول

The way to elevate a new process programmatically is to ask the shell to execute the executable file using the verb runas. That's the only supported way to do it. In order to pass the runas verb to the shell, you need to call a suitable Win32 API function. Possible candidates include ShellExecute and ShellExecuteEx.

The UseShellExecute property determines which API call is used when you call Process.Start. If UseShellExecute is true, then ShellExecuteEx is called. Otherwise CreateProcess is called.

So, when you set UseShellExecute to false, you switched to using CreateProcess. And CreateProcess does not have any mechanism to elevate the new process. So when UseShellExecute is false, the runas verb that you provided is simply ignored because CreateProcess does not receive shell verbs.

نصائح أخرى

The behaviour is because Process.Start uses one of two APIs internally: CreateProcess or ShellExecuteEx. Only the latter supports UAC elevation, which us why you must set UseShellExecute = true.

As an interesting aside, there is another way to achieve UAC elevation without directly starting a new process. You can write an out-of-process COM component to perform the actual work that needs to run elevated. Then, when you instantiate the component, it runs in an elevated process (after the UAC prompt is displayed). Of course, it's not easy to write out-of-process COM components in .NET without using C++/CLI. But see this post for more information.

Microsoft Channel 9 video that explains the guts of UAC.

Architecturally, only ShellExecute has the knowledge of how to launch Consent.exe (the UAC dialog). So that's why you must use it.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top