11using System ;
2+ using System . ComponentModel ;
23using System . Collections . Generic ;
34using System . Diagnostics ;
45using System . IO ;
@@ -18,6 +19,7 @@ static extern bool CreateProcess(string lpApplicationName,
1819 uint dwCreationFlags , IntPtr lpEnvironment , string lpCurrentDirectory ,
1920 [ In ] ref STARTUPINFO lpStartupInfo ,
2021 out PROCESS_INFORMATION lpProcessInformation ) ;
22+ const int ERROR_ELEVATION_REQUIRED = 740 ;
2123
2224 [ StructLayout ( LayoutKind . Sequential , CharSet = CharSet . Unicode ) ]
2325 struct STARTUPINFO {
@@ -97,7 +99,24 @@ static int Main(string[] args) {
9799 lpStartupInfo : ref si ,
98100 lpProcessInformation : out pi ) ) {
99101
100- return Marshal . GetLastWin32Error ( ) ;
102+ var error = Marshal . GetLastWin32Error ( ) ;
103+ if ( error == ERROR_ELEVATION_REQUIRED ) {
104+ // Unfortunately, ShellExecute() does not allow us to run program without
105+ // CREATE_NEW_CONSOLE, so we can not replace CreateProcess() completely.
106+ // The good news is we are okay with CREATE_NEW_CONSOLE when we run program with elevation.
107+ Process process = new Process ( ) ;
108+ process . StartInfo = new ProcessStartInfo ( path , cmd_args ) ;
109+ process . StartInfo . UseShellExecute = true ;
110+ try {
111+ process . Start ( ) ;
112+ }
113+ catch ( Win32Exception exception ) {
114+ return exception . ErrorCode ;
115+ }
116+ process . WaitForExit ( ) ;
117+ return process . ExitCode ;
118+ }
119+ return error ;
101120 }
102121
103122 WaitForSingleObject ( pi . hProcess , INFINITE ) ;
0 commit comments