├── .gitignore
├── DemoModernService
├── DemoModernService.cs
├── DemoModernService.csproj
├── Program.cs
├── createService.cmd
└── deleteService.cmd
├── DemoService
├── App.config
├── DemoService.Designer.cs
├── DemoService.cs
├── DemoService.csproj
├── Program.cs
├── ProjectInstaller.Designer.cs
├── ProjectInstaller.cs
├── ProjectInstaller.resx
├── Properties
│ └── AssemblyInfo.cs
├── createService.bat
└── deleteService.bat
├── LICENSE
├── ProcessExtensions
├── ProcessExtensions.cs
└── ProcessExtensions.csproj
├── README.md
└── solution.sln
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Ww][Ii][Nn]32/
27 | [Aa][Rr][Mm]/
28 | [Aa][Rr][Mm]64/
29 | bld/
30 | [Bb]in/
31 | [Oo]bj/
32 | [Ll]og/
33 | [Ll]ogs/
34 |
35 | # Visual Studio 2015/2017 cache/options directory
36 | .vs/
37 | # Uncomment if you have tasks that create the project's static files in wwwroot
38 | #wwwroot/
39 |
40 | # Visual Studio 2017 auto generated files
41 | Generated\ Files/
42 |
43 | # MSTest test Results
44 | [Tt]est[Rr]esult*/
45 | [Bb]uild[Ll]og.*
46 |
47 | # NUnit
48 | *.VisualState.xml
49 | TestResult.xml
50 | nunit-*.xml
51 |
52 | # Build Results of an ATL Project
53 | [Dd]ebugPS/
54 | [Rr]eleasePS/
55 | dlldata.c
56 |
57 | # Benchmark Results
58 | BenchmarkDotNet.Artifacts/
59 |
60 | # .NET Core
61 | project.lock.json
62 | project.fragment.lock.json
63 | artifacts/
64 |
65 | # ASP.NET Scaffolding
66 | ScaffoldingReadMe.txt
67 |
68 | # StyleCop
69 | StyleCopReport.xml
70 |
71 | # Files built by Visual Studio
72 | *_i.c
73 | *_p.c
74 | *_h.h
75 | *.ilk
76 | *.meta
77 | *.obj
78 | *.iobj
79 | *.pch
80 | *.pdb
81 | *.ipdb
82 | *.pgc
83 | *.pgd
84 | *.rsp
85 | *.sbr
86 | *.tlb
87 | *.tli
88 | *.tlh
89 | *.tmp
90 | *.tmp_proj
91 | *_wpftmp.csproj
92 | *.log
93 | *.tlog
94 | *.vspscc
95 | *.vssscc
96 | .builds
97 | *.pidb
98 | *.svclog
99 | *.scc
100 |
101 | # Chutzpah Test files
102 | _Chutzpah*
103 |
104 | # Visual C++ cache files
105 | ipch/
106 | *.aps
107 | *.ncb
108 | *.opendb
109 | *.opensdf
110 | *.sdf
111 | *.cachefile
112 | *.VC.db
113 | *.VC.VC.opendb
114 |
115 | # Visual Studio profiler
116 | *.psess
117 | *.vsp
118 | *.vspx
119 | *.sap
120 |
121 | # Visual Studio Trace Files
122 | *.e2e
123 |
124 | # TFS 2012 Local Workspace
125 | $tf/
126 |
127 | # Guidance Automation Toolkit
128 | *.gpState
129 |
130 | # ReSharper is a .NET coding add-in
131 | _ReSharper*/
132 | *.[Rr]e[Ss]harper
133 | *.DotSettings.user
134 |
135 | # TeamCity is a build add-in
136 | _TeamCity*
137 |
138 | # DotCover is a Code Coverage Tool
139 | *.dotCover
140 |
141 | # AxoCover is a Code Coverage Tool
142 | .axoCover/*
143 | !.axoCover/settings.json
144 |
145 | # Coverlet is a free, cross platform Code Coverage Tool
146 | coverage*.json
147 | coverage*.xml
148 | coverage*.info
149 |
150 | # Visual Studio code coverage results
151 | *.coverage
152 | *.coveragexml
153 |
154 | # NCrunch
155 | _NCrunch_*
156 | .*crunch*.local.xml
157 | nCrunchTemp_*
158 |
159 | # MightyMoose
160 | *.mm.*
161 | AutoTest.Net/
162 |
163 | # Web workbench (sass)
164 | .sass-cache/
165 |
166 | # Installshield output folder
167 | [Ee]xpress/
168 |
169 | # DocProject is a documentation generator add-in
170 | DocProject/buildhelp/
171 | DocProject/Help/*.HxT
172 | DocProject/Help/*.HxC
173 | DocProject/Help/*.hhc
174 | DocProject/Help/*.hhk
175 | DocProject/Help/*.hhp
176 | DocProject/Help/Html2
177 | DocProject/Help/html
178 |
179 | # Click-Once directory
180 | publish/
181 |
182 | # Publish Web Output
183 | *.[Pp]ublish.xml
184 | *.azurePubxml
185 | # Note: Comment the next line if you want to checkin your web deploy settings,
186 | # but database connection strings (with potential passwords) will be unencrypted
187 | *.pubxml
188 | *.publishproj
189 |
190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
191 | # checkin your Azure Web App publish settings, but sensitive information contained
192 | # in these scripts will be unencrypted
193 | PublishScripts/
194 |
195 | # NuGet Packages
196 | *.nupkg
197 | # NuGet Symbol Packages
198 | *.snupkg
199 | # The packages folder can be ignored because of Package Restore
200 | **/[Pp]ackages/*
201 | # except build/, which is used as an MSBuild target.
202 | !**/[Pp]ackages/build/
203 | # Uncomment if necessary however generally it will be regenerated when needed
204 | #!**/[Pp]ackages/repositories.config
205 | # NuGet v3's project.json files produces more ignorable files
206 | *.nuget.props
207 | *.nuget.targets
208 |
209 | # Microsoft Azure Build Output
210 | csx/
211 | *.build.csdef
212 |
213 | # Microsoft Azure Emulator
214 | ecf/
215 | rcf/
216 |
217 | # Windows Store app package directories and files
218 | AppPackages/
219 | BundleArtifacts/
220 | Package.StoreAssociation.xml
221 | _pkginfo.txt
222 | *.appx
223 | *.appxbundle
224 | *.appxupload
225 |
226 | # Visual Studio cache files
227 | # files ending in .cache can be ignored
228 | *.[Cc]ache
229 | # but keep track of directories ending in .cache
230 | !?*.[Cc]ache/
231 |
232 | # Others
233 | ClientBin/
234 | ~$*
235 | *~
236 | *.dbmdl
237 | *.dbproj.schemaview
238 | *.jfm
239 | *.pfx
240 | *.publishsettings
241 | orleans.codegen.cs
242 |
243 | # Including strong name files can present a security risk
244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
245 | #*.snk
246 |
247 | # Since there are multiple workflows, uncomment next line to ignore bower_components
248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
249 | #bower_components/
250 |
251 | # RIA/Silverlight projects
252 | Generated_Code/
253 |
254 | # Backup & report files from converting an old project file
255 | # to a newer Visual Studio version. Backup files are not needed,
256 | # because we have git ;-)
257 | _UpgradeReport_Files/
258 | Backup*/
259 | UpgradeLog*.XML
260 | UpgradeLog*.htm
261 | ServiceFabricBackup/
262 | *.rptproj.bak
263 |
264 | # SQL Server files
265 | *.mdf
266 | *.ldf
267 | *.ndf
268 |
269 | # Business Intelligence projects
270 | *.rdl.data
271 | *.bim.layout
272 | *.bim_*.settings
273 | *.rptproj.rsuser
274 | *- [Bb]ackup.rdl
275 | *- [Bb]ackup ([0-9]).rdl
276 | *- [Bb]ackup ([0-9][0-9]).rdl
277 |
278 | # Microsoft Fakes
279 | FakesAssemblies/
280 |
281 | # GhostDoc plugin setting file
282 | *.GhostDoc.xml
283 |
284 | # Node.js Tools for Visual Studio
285 | .ntvs_analysis.dat
286 | node_modules/
287 |
288 | # Visual Studio 6 build log
289 | *.plg
290 |
291 | # Visual Studio 6 workspace options file
292 | *.opt
293 |
294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
295 | *.vbw
296 |
297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.)
298 | *.vbp
299 |
300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project)
301 | *.dsw
302 | *.dsp
303 |
304 | # Visual Studio 6 technical files
305 | *.ncb
306 | *.aps
307 |
308 | # Visual Studio LightSwitch build output
309 | **/*.HTMLClient/GeneratedArtifacts
310 | **/*.DesktopClient/GeneratedArtifacts
311 | **/*.DesktopClient/ModelManifest.xml
312 | **/*.Server/GeneratedArtifacts
313 | **/*.Server/ModelManifest.xml
314 | _Pvt_Extensions
315 |
316 | # Paket dependency manager
317 | .paket/paket.exe
318 | paket-files/
319 |
320 | # FAKE - F# Make
321 | .fake/
322 |
323 | # CodeRush personal settings
324 | .cr/personal
325 |
326 | # Python Tools for Visual Studio (PTVS)
327 | __pycache__/
328 | *.pyc
329 |
330 | # Cake - Uncomment if you are using it
331 | # tools/**
332 | # !tools/packages.config
333 |
334 | # Tabs Studio
335 | *.tss
336 |
337 | # Telerik's JustMock configuration file
338 | *.jmconfig
339 |
340 | # BizTalk build output
341 | *.btp.cs
342 | *.btm.cs
343 | *.odx.cs
344 | *.xsd.cs
345 |
346 | # OpenCover UI analysis results
347 | OpenCover/
348 |
349 | # Azure Stream Analytics local run output
350 | ASALocalRun/
351 |
352 | # MSBuild Binary and Structured Log
353 | *.binlog
354 |
355 | # NVidia Nsight GPU debugger configuration file
356 | *.nvuser
357 |
358 | # MFractors (Xamarin productivity tool) working folder
359 | .mfractor/
360 |
361 | # Local History for Visual Studio
362 | .localhistory/
363 |
364 | # Visual Studio History (VSHistory) files
365 | .vshistory/
366 |
367 | # BeatPulse healthcheck temp database
368 | healthchecksdb
369 |
370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
371 | MigrationBackup/
372 |
373 | # Ionide (cross platform F# VS Code tools) working folder
374 | .ionide/
375 |
376 | # Fody - auto-generated XML schema
377 | FodyWeavers.xsd
378 |
379 | # VS Code files for those working on multiple tools
380 | .vscode/*
381 | !.vscode/settings.json
382 | !.vscode/tasks.json
383 | !.vscode/launch.json
384 | !.vscode/extensions.json
385 | *.code-workspace
386 |
387 | # Local History for Visual Studio Code
388 | .history/
389 |
390 | # Windows Installer files from build outputs
391 | *.cab
392 | *.msi
393 | *.msix
394 | *.msm
395 | *.msp
396 |
397 | # JetBrains Rider
398 | *.sln.iml
399 | /local_notes.md
400 |
--------------------------------------------------------------------------------
/DemoModernService/DemoModernService.cs:
--------------------------------------------------------------------------------
1 |
2 | using Microsoft.Extensions.Hosting;
3 | using murrayju.ProcessExtensions;
4 |
5 | namespace DemoModernService;
6 |
7 | internal class DemoModernService : BackgroundService
8 | {
9 | protected override async Task ExecuteAsync(CancellationToken stoppingToken)
10 | {
11 | ProcessExtensions.StartProcessAsCurrentUser("calc.exe");
12 | }
13 | }
--------------------------------------------------------------------------------
/DemoModernService/DemoModernService.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net8.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 | Always
21 |
22 |
23 | Always
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/DemoModernService/Program.cs:
--------------------------------------------------------------------------------
1 |
2 | using Microsoft.Extensions.DependencyInjection;
3 | using Microsoft.Extensions.Hosting;
4 |
5 | namespace DemoModernService;
6 |
7 | internal class Program
8 | {
9 | static async Task Main(string[] args)
10 | {
11 | var host = Host.CreateDefaultBuilder(args)
12 | .UseWindowsService(opt =>
13 | {
14 | opt.ServiceName = "DemoModernService";
15 | })
16 | .ConfigureServices(svc =>
17 | {
18 | svc.AddHostedService();
19 | })
20 | .Build();
21 |
22 | await host.RunAsync();
23 | }
24 | }
--------------------------------------------------------------------------------
/DemoModernService/createService.cmd:
--------------------------------------------------------------------------------
1 | @echo off
2 | @rem Intended to run from the same directory (e.g. bin); build should copy to bin.
3 | openfiles.exe 1>nul 2>&1
4 | if not %errorlevel% equ 0 goto :fail
5 | sc create "DemoModernService" binpath= "%~dp0DemoModernService.exe" displayname= "murrayju.ProcessExtensions Modern .NET Demo"
6 | sc start "DemoModernService"
7 | goto:eof
8 | :fail
9 | echo:
10 | echo Failed. Run as Administrator.
11 | echo:
12 | :eof
13 |
--------------------------------------------------------------------------------
/DemoModernService/deleteService.cmd:
--------------------------------------------------------------------------------
1 | @echo off
2 | @rem Intended to run from the same directory (e.g. bin); build should copy to bin.
3 | openfiles.exe 1>nul 2>&1
4 | if not %errorlevel% equ 0 goto :fail
5 | sc stop "DemoModernService"
6 | sc delete "DemoModernService"
7 | goto:eof
8 | :fail
9 | echo:
10 | echo Failed. Run as Administrator.
11 | echo:
12 | :eof
--------------------------------------------------------------------------------
/DemoService/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/DemoService/DemoService.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace demo
2 | {
3 | partial class DemoService
4 | {
5 | ///
6 | /// Required designer variable.
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// Clean up any resources being used.
12 | ///
13 | /// true if managed resources should be disposed; otherwise, false.
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Component Designer generated code
24 |
25 | ///
26 | /// Required method for Designer support - do not modify
27 | /// the contents of this method with the code editor.
28 | ///
29 | private void InitializeComponent()
30 | {
31 | components = new System.ComponentModel.Container();
32 | this.ServiceName = "Service1";
33 | }
34 |
35 | #endregion
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/DemoService/DemoService.cs:
--------------------------------------------------------------------------------
1 | using murrayju.ProcessExtensions;
2 | using System.ServiceProcess;
3 |
4 | namespace demo
5 | {
6 | public partial class DemoService : ServiceBase
7 | {
8 | public DemoService()
9 | {
10 | InitializeComponent();
11 | }
12 |
13 | protected override void OnStart(string[] args)
14 | {
15 | ProcessExtensions.StartProcessAsCurrentUser("calc.exe");
16 | }
17 |
18 | protected override void OnStop()
19 | {
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/DemoService/DemoService.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {68EA76FB-33DA-4A20-B54A-7CBF1A3EDBBE}
8 | Exe
9 | demo
10 | DemoService
11 | v4.8.1
12 | 512
13 | true
14 | true
15 |
16 |
17 | AnyCPU
18 | true
19 | full
20 | false
21 | bin\Debug\
22 | DEBUG;TRACE
23 | prompt
24 | 4
25 |
26 |
27 | AnyCPU
28 | pdbonly
29 | true
30 | bin\Release\
31 | TRACE
32 | prompt
33 | 4
34 |
35 |
36 |
37 |
38 | ..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8.1\System.Configuration.Install.dll
39 |
40 |
41 |
42 | ..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8.1\System.ServiceProcess.dll
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 | Component
54 |
55 |
56 |
57 |
58 | Component
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 | Always
67 |
68 |
69 | Always
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 | {75ee3b51-5a96-473c-9e68-c36b728a6e2b}
78 | ProcessExtensions
79 |
80 |
81 |
82 |
--------------------------------------------------------------------------------
/DemoService/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.ServiceProcess;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace demo
9 | {
10 | static class Program
11 | {
12 | ///
13 | /// The main entry point for the application.
14 | ///
15 | static void Main()
16 | {
17 | ServiceBase[] ServicesToRun;
18 | ServicesToRun = new ServiceBase[]
19 | {
20 | new DemoService()
21 | };
22 | ServiceBase.Run(ServicesToRun);
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/DemoService/ProjectInstaller.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace DemoService
2 | {
3 | partial class ProjectInstaller
4 | {
5 | ///
6 | /// Required designer variable.
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// Clean up any resources being used.
12 | ///
13 | /// true if managed resources should be disposed; otherwise, false.
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Component Designer generated code
24 |
25 | ///
26 | /// Required method for Designer support - do not modify
27 | /// the contents of this method with the code editor.
28 | ///
29 | private void InitializeComponent()
30 | {
31 | this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller();
32 | this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller();
33 | //
34 | // serviceProcessInstaller1
35 | //
36 | this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;
37 | this.serviceProcessInstaller1.Password = null;
38 | this.serviceProcessInstaller1.Username = null;
39 | //
40 | // serviceInstaller1
41 | //
42 | this.serviceInstaller1.Description = "An example service";
43 | this.serviceInstaller1.DisplayName = "DemoService";
44 | this.serviceInstaller1.ServiceName = "DemoService";
45 | this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
46 | //
47 | // ProjectInstaller
48 | //
49 | this.Installers.AddRange(new System.Configuration.Install.Installer[] {
50 | this.serviceProcessInstaller1,
51 | this.serviceInstaller1});
52 |
53 | }
54 |
55 | #endregion
56 |
57 | private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1;
58 | private System.ServiceProcess.ServiceInstaller serviceInstaller1;
59 | }
60 | }
--------------------------------------------------------------------------------
/DemoService/ProjectInstaller.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections;
3 | using System.Collections.Generic;
4 | using System.ComponentModel;
5 | using System.Configuration.Install;
6 | using System.Linq;
7 | using System.Threading.Tasks;
8 |
9 | namespace DemoService
10 | {
11 | [RunInstaller(true)]
12 | public partial class ProjectInstaller : System.Configuration.Install.Installer
13 | {
14 | public ProjectInstaller()
15 | {
16 | InitializeComponent();
17 | }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/DemoService/ProjectInstaller.resx:
--------------------------------------------------------------------------------
1 |
2 |
3 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 | text/microsoft-resx
110 |
111 |
112 | 2.0
113 |
114 |
115 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
116 |
117 |
118 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
119 |
120 |
121 | 17, 17
122 |
123 |
124 | 196, 17
125 |
126 |
127 | False
128 |
129 |
--------------------------------------------------------------------------------
/DemoService/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("DemoService")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("DemoService")]
13 | [assembly: AssemblyCopyright("Copyright © 2023")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("68ea76fb-33da-4a20-b54a-7cbf1a3edbbe")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/DemoService/createService.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | @rem Intended to run from the same directory (e.g. bin); build should copy to bin.
3 | %windir%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe .\DemoService.exe
4 | sc start DemoService
5 |
--------------------------------------------------------------------------------
/DemoService/deleteService.bat:
--------------------------------------------------------------------------------
1 | @echo off
2 | @rem Intended to run from the same directory (e.g. bin); build should copy to bin.
3 | sc stop DemoService
4 | %windir%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /u .\DemoService.exe
5 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2014 Justin Murray
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/ProcessExtensions/ProcessExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Runtime.InteropServices;
4 |
5 | namespace murrayju.ProcessExtensions
6 | {
7 | public class ProcessCreationException : Exception
8 | {
9 | public ProcessCreationException(string msg) : base(msg) { }
10 | }
11 |
12 | public static class ProcessExtensions
13 | {
14 | #region Win32 Constants
15 |
16 | private const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
17 | private const int CREATE_NO_WINDOW = 0x08000000;
18 |
19 | private const int CREATE_NEW_CONSOLE = 0x00000010;
20 |
21 | private const uint INVALID_SESSION_ID = 0xFFFFFFFF;
22 | private static readonly IntPtr WTS_CURRENT_SERVER_HANDLE = IntPtr.Zero;
23 | private const int STARTF_USESHOWWINDOW = 0x00000001;
24 |
25 | #endregion
26 |
27 | #region DllImports
28 |
29 | [DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
30 | private static extern bool CreateProcessAsUser(
31 | IntPtr hToken,
32 | String lpApplicationName,
33 | String lpCommandLine,
34 | IntPtr lpProcessAttributes,
35 | IntPtr lpThreadAttributes,
36 | bool bInheritHandle,
37 | uint dwCreationFlags,
38 | IntPtr lpEnvironment,
39 | String lpCurrentDirectory,
40 | ref STARTUPINFO lpStartupInfo,
41 | out PROCESS_INFORMATION lpProcessInformation);
42 |
43 | [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
44 | private static extern bool DuplicateTokenEx(
45 | IntPtr ExistingTokenHandle,
46 | uint dwDesiredAccess,
47 | IntPtr lpThreadAttributes,
48 | int TokenType,
49 | int ImpersonationLevel,
50 | ref IntPtr DuplicateTokenHandle);
51 |
52 | [DllImport("userenv.dll", SetLastError = true)]
53 | private static extern bool CreateEnvironmentBlock(ref IntPtr lpEnvironment, IntPtr hToken, bool bInherit);
54 |
55 | [DllImport("userenv.dll", SetLastError = true)]
56 | [return: MarshalAs(UnmanagedType.Bool)]
57 | private static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment);
58 |
59 | [DllImport("kernel32.dll", SetLastError = true)]
60 | private static extern bool CloseHandle(IntPtr hSnapshot);
61 |
62 | [DllImport("kernel32.dll")]
63 | private static extern uint WTSGetActiveConsoleSessionId();
64 |
65 | [DllImport("Wtsapi32.dll")]
66 | private static extern uint WTSQueryUserToken(uint SessionId, ref IntPtr phToken);
67 |
68 | [DllImport("wtsapi32.dll", SetLastError = true)]
69 | private static extern int WTSEnumerateSessions(
70 | IntPtr hServer,
71 | int Reserved,
72 | int Version,
73 | ref IntPtr ppSessionInfo,
74 | ref int pCount);
75 |
76 | [DllImport("Wtsapi32.dll")]
77 | private static extern void WTSFreeMemory(IntPtr ppSessionInfo);
78 |
79 | #endregion
80 |
81 | #region Win32 Structs
82 |
83 | private enum SW
84 | {
85 | SW_HIDE = 0,
86 | SW_SHOWNORMAL = 1,
87 | SW_NORMAL = 1,
88 | SW_SHOWMINIMIZED = 2,
89 | SW_SHOWMAXIMIZED = 3,
90 | SW_MAXIMIZE = 3,
91 | SW_SHOWNOACTIVATE = 4,
92 | SW_SHOW = 5,
93 | SW_MINIMIZE = 6,
94 | SW_SHOWMINNOACTIVE = 7,
95 | SW_SHOWNA = 8,
96 | SW_RESTORE = 9,
97 | SW_SHOWDEFAULT = 10,
98 | SW_MAX = 10
99 | }
100 |
101 | private enum WTS_CONNECTSTATE_CLASS
102 | {
103 | WTSActive,
104 | WTSConnected,
105 | WTSConnectQuery,
106 | WTSShadow,
107 | WTSDisconnected,
108 | WTSIdle,
109 | WTSListen,
110 | WTSReset,
111 | WTSDown,
112 | WTSInit
113 | }
114 |
115 | [StructLayout(LayoutKind.Sequential)]
116 | private struct PROCESS_INFORMATION
117 | {
118 | public IntPtr hProcess;
119 | public IntPtr hThread;
120 | public uint dwProcessId;
121 | public uint dwThreadId;
122 | }
123 |
124 | private enum SECURITY_IMPERSONATION_LEVEL
125 | {
126 | SecurityAnonymous = 0,
127 | SecurityIdentification = 1,
128 | SecurityImpersonation = 2,
129 | SecurityDelegation = 3,
130 | }
131 |
132 | [StructLayout(LayoutKind.Sequential)]
133 | private struct STARTUPINFO
134 | {
135 | public int cb;
136 | public String lpReserved;
137 | public String lpDesktop;
138 | public String lpTitle;
139 | public uint dwX;
140 | public uint dwY;
141 | public uint dwXSize;
142 | public uint dwYSize;
143 | public uint dwXCountChars;
144 | public uint dwYCountChars;
145 | public uint dwFillAttribute;
146 | public uint dwFlags;
147 | public short wShowWindow;
148 | public short cbReserved2;
149 | public IntPtr lpReserved2;
150 | public IntPtr hStdInput;
151 | public IntPtr hStdOutput;
152 | public IntPtr hStdError;
153 | }
154 |
155 | private enum TOKEN_TYPE
156 | {
157 | TokenPrimary = 1,
158 | TokenImpersonation = 2
159 | }
160 |
161 | [StructLayout(LayoutKind.Sequential)]
162 | private struct WTS_SESSION_INFO
163 | {
164 | public readonly UInt32 SessionID;
165 |
166 | [MarshalAs(UnmanagedType.LPStr)]
167 | public readonly String pWinStationName;
168 |
169 | public readonly WTS_CONNECTSTATE_CLASS State;
170 | }
171 |
172 | #endregion
173 |
174 | // Gets the user token from the currently active session
175 | private static bool GetSessionUserToken(ref IntPtr phUserToken)
176 | {
177 | var bResult = false;
178 | var hImpersonationToken = IntPtr.Zero;
179 | var activeSessionId = INVALID_SESSION_ID;
180 | var pSessionInfo = IntPtr.Zero;
181 | var sessionCount = 0;
182 |
183 | // Get a handle to the user access token for the current active session.
184 | if (WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, ref pSessionInfo, ref sessionCount) != 0)
185 | {
186 | var arrayElementSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));
187 | var current = pSessionInfo;
188 |
189 | for (var i = 0; i < sessionCount; i++)
190 | {
191 | var si = (WTS_SESSION_INFO)Marshal.PtrToStructure((IntPtr)current, typeof(WTS_SESSION_INFO));
192 | current += arrayElementSize;
193 |
194 | if (si.State == WTS_CONNECTSTATE_CLASS.WTSActive)
195 | {
196 | activeSessionId = si.SessionID;
197 | }
198 | }
199 |
200 | WTSFreeMemory(pSessionInfo);
201 | }
202 |
203 | // If enumerating did not work, fall back to the old method
204 | if (activeSessionId == INVALID_SESSION_ID)
205 | {
206 | activeSessionId = WTSGetActiveConsoleSessionId();
207 | }
208 |
209 | if (WTSQueryUserToken(activeSessionId, ref hImpersonationToken) != 0)
210 | {
211 | // Convert the impersonation token to a primary token
212 | bResult = DuplicateTokenEx(hImpersonationToken, 0, IntPtr.Zero,
213 | (int)SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, (int)TOKEN_TYPE.TokenPrimary,
214 | ref phUserToken);
215 |
216 | CloseHandle(hImpersonationToken);
217 | }
218 |
219 | return bResult;
220 | }
221 |
222 | public static bool StartProcessAsCurrentUser(string appPath, string cmdLine = null, string workDir = null, bool visible = true)
223 | {
224 | var hUserToken = IntPtr.Zero;
225 | var startInfo = new STARTUPINFO();
226 | var procInfo = new PROCESS_INFORMATION();
227 | var pEnv = IntPtr.Zero;
228 | int iResultOfCreateProcessAsUser;
229 |
230 | startInfo.cb = Marshal.SizeOf(typeof(STARTUPINFO));
231 |
232 | try
233 | {
234 | if (!GetSessionUserToken(ref hUserToken))
235 | {
236 | throw new ProcessCreationException("StartProcessAsCurrentUser: GetSessionUserToken failed.");
237 | }
238 |
239 | uint dwCreationFlags = CREATE_UNICODE_ENVIRONMENT | (uint)(visible ? CREATE_NEW_CONSOLE : CREATE_NO_WINDOW);
240 | startInfo.dwFlags = STARTF_USESHOWWINDOW;
241 | startInfo.wShowWindow = (short)(visible ? SW.SW_SHOW : SW.SW_HIDE);
242 | startInfo.lpDesktop = "winsta0\\default";
243 |
244 | if (!CreateEnvironmentBlock(ref pEnv, hUserToken, false))
245 | {
246 | throw new ProcessCreationException("StartProcessAsCurrentUser: CreateEnvironmentBlock failed.");
247 | }
248 |
249 | if (workDir != null)
250 | {
251 | Directory.SetCurrentDirectory(workDir);
252 | }
253 |
254 | if (!CreateProcessAsUser(hUserToken,
255 | appPath, // Application Name
256 | cmdLine, // Command Line
257 | IntPtr.Zero,
258 | IntPtr.Zero,
259 | false,
260 | dwCreationFlags,
261 | pEnv,
262 | workDir, // Working directory
263 | ref startInfo,
264 | out procInfo))
265 | {
266 | iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
267 | throw new ProcessCreationException("StartProcessAsCurrentUser: CreateProcessAsUser failed. Error Code -" + iResultOfCreateProcessAsUser);
268 | }
269 |
270 | iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();
271 | }
272 | finally
273 | {
274 | CloseHandle(hUserToken);
275 | if (pEnv != IntPtr.Zero)
276 | {
277 | DestroyEnvironmentBlock(pEnv);
278 | }
279 | CloseHandle(procInfo.hThread);
280 | CloseHandle(procInfo.hProcess);
281 | }
282 |
283 | return true;
284 | }
285 |
286 | }
287 | }
288 |
--------------------------------------------------------------------------------
/ProcessExtensions/ProcessExtensions.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netstandard2.0
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CreateProcessAsUser
2 |
3 | 
4 |
5 | ---
6 |
7 | ### 🚧 Looking for maintainers 🚧
8 | > :loudspeaker: **We are actively seeking collaborators to help maintain and improve this project!**
9 |
10 | This library was created 10+ years ago when I was actively working on Windows services. I have since moved on to other things, and I'm not in a position to easily maintain this project, which is still actively used by the community. If you are interested in helping, please reach out!
11 |
12 | ---
13 |
14 | This uses the Win32 apis to:
15 |
16 | 1. Find the currently active user session
17 | 2. Spawn a new process in that session
18 |
19 | This allows a process running in a different session (such as a windows service) to start a process with a graphical user interface that the user must see.
20 |
21 | Note that the process must have the appropriate (admin) privileges for this to work correctly. For [WTSQueryUserToken](https://github.com/murrayju/CreateProcessAsUser/blob/0381db2e8fb36f48794c073e87f773f7ca1ae039/ProcessExtensions/ProcessExtensions.cs#L197) you will need the __SE_TCB_NAME__ privilege, which is typically only held by Services running under the LocalSystem account ( [SO Link](https://stackoverflow.com/a/1289126/1872399) ).
22 |
23 | ## Usage
24 | ```C#
25 | using murrayju.ProcessExtensions;
26 | // ...
27 | ProcessExtensions.StartProcessAsCurrentUser("calc.exe");
28 | ```
29 |
30 | ### Parameters
31 | The second argument is used to pass the command line arguments as a string. Depending on the target application, `argv[0]` might be expected to be the executable name, or it might be the first parameter. See [this stack overflow answer](https://stackoverflow.com/a/14001282) for details. When in doubt, try it both ways.
32 |
33 | ## Demo Projects
34 | The `DemoService` project uses .NET Framework 4.8. Building the demo will copy the batch files to the build target.
35 |
36 | Similarly, the `DemoModernService` project uses .NET 8.0, and a build will copy the batch files to the build target.
37 |
38 | For either version, CD to the bin directory and run `createService` to install and start the service. It will launch `calc.exe` as soon as it starts. After that, run `deleteService` to stop and uninstall the service.
39 |
40 |
--------------------------------------------------------------------------------
/solution.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.8.34330.188
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DemoService", "DemoService\DemoService.csproj", "{68EA76FB-33DA-4A20-B54A-7CBF1A3EDBBE}"
7 | EndProject
8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DemoModernService", "DemoModernService\DemoModernService.csproj", "{E9053B19-2C9F-4760-950D-FB33711C77D9}"
9 | EndProject
10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProcessExtensions", "ProcessExtensions\ProcessExtensions.csproj", "{75EE3B51-5A96-473C-9E68-C36B728A6E2B}"
11 | EndProject
12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{226E4595-B7A9-400C-9FF2-FE0DACFA4BEC}"
13 | ProjectSection(SolutionItems) = preProject
14 | README.md = README.md
15 | EndProjectSection
16 | EndProject
17 | Global
18 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
19 | Debug|Any CPU = Debug|Any CPU
20 | Release|Any CPU = Release|Any CPU
21 | EndGlobalSection
22 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
23 | {68EA76FB-33DA-4A20-B54A-7CBF1A3EDBBE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
24 | {68EA76FB-33DA-4A20-B54A-7CBF1A3EDBBE}.Debug|Any CPU.Build.0 = Debug|Any CPU
25 | {68EA76FB-33DA-4A20-B54A-7CBF1A3EDBBE}.Release|Any CPU.ActiveCfg = Release|Any CPU
26 | {68EA76FB-33DA-4A20-B54A-7CBF1A3EDBBE}.Release|Any CPU.Build.0 = Release|Any CPU
27 | {E9053B19-2C9F-4760-950D-FB33711C77D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
28 | {E9053B19-2C9F-4760-950D-FB33711C77D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
29 | {E9053B19-2C9F-4760-950D-FB33711C77D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
30 | {E9053B19-2C9F-4760-950D-FB33711C77D9}.Release|Any CPU.Build.0 = Release|Any CPU
31 | {75EE3B51-5A96-473C-9E68-C36B728A6E2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
32 | {75EE3B51-5A96-473C-9E68-C36B728A6E2B}.Debug|Any CPU.Build.0 = Debug|Any CPU
33 | {75EE3B51-5A96-473C-9E68-C36B728A6E2B}.Release|Any CPU.ActiveCfg = Release|Any CPU
34 | {75EE3B51-5A96-473C-9E68-C36B728A6E2B}.Release|Any CPU.Build.0 = Release|Any CPU
35 | EndGlobalSection
36 | GlobalSection(SolutionProperties) = preSolution
37 | HideSolutionNode = FALSE
38 | EndGlobalSection
39 | GlobalSection(ExtensibilityGlobals) = postSolution
40 | SolutionGuid = {559520CD-416C-401B-9B7D-3690FF2D73FD}
41 | EndGlobalSection
42 | EndGlobal
43 |
--------------------------------------------------------------------------------