简体   繁体   中英

How to force user to user Administrator account in WinForms

I have simple WinForms application where modifying Windows Registry. The problem is that in Vista / Windows 7 I need to force user to switch to administrator.

I do not want to force user to Run as Administrator form start of the application. I want him to do it when there is necessity to write to registry.

Best case scenario would be to reach exacly the same message which appear in lot's of Setups, when user need to 'switch' to Administrator so there is no necessity to Run as Administrator form beginning.

How I can achieve this in .Net ?

Partitioning is the way to go if the application sometimes doesn't do the Registry thing and sometimes does. The three keys to partitioning are (1) have a manifest on the second exe, as Ho says, (2) put a shield on the button/menu item so the user expects the elevation, and (3) launch it with ShellExecute (before calling Start, set the UseShellExecuteFlag to true) so that the manifest is used.

However, before going to the trouble of splitting your app, I would ask two questions. First, is it ever used for non administrative purposes or does every user always "click that button" and need to elevate? If so, then just put an admin manifest on the app and don't partition it. Second, are you sure to need to write to that part of the registry? Could you move your key to something under HKCU? If you can, then you don't need elevation any more and everyone's happier. I always like to consider those possibilites first since they mean less code and less testing than partioning does.

As Aaronaught says, I don't think it's possible for a process to to request to elevate itself. One way around this is that you split your process into two apps, one is the normal one that does most of the work and the other one only does the registry writes and this one has a manifest that contains something like

<requestedExecutionLevel level="requireAdministrator"/>

As far as I know, there's no API to elevate a process. It happens automatically when a process tries to launch another process in elevated mode.

This is also how it works with the Windows Installer. I'm not sure if it literally starts another elevated process or just creates an elevated COM object, but it's effectively the same thing.

I personally wouldn't resort to this hackish workaround to elevate your process mid-execution; if your process may require elevation, then make that explicit with a manifest and let the consent message pop up on startup. But if you absolutely must do this, then that's how - you need to launch an elevated process from within your app.

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