Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open cmd from windows service?

I am creating a Windows Service and using C#. I want open cmd.exe from the service. My operating system is Windows 8. Is it possible from a Windows Service, or is there another alternative for that.

(I want to open cmd.exe after some interval - that's why I chose a windows service)

like image 217
Jui Test Avatar asked Dec 03 '15 06:12

Jui Test


People also ask

How do I start a command prompt as a service?

Open Start. Search for Command Prompt, right-click the top result, and select the Run as administrator option. Type the following command to enable a service and press Enter: sc config "SERVICE-NAME" start=auto In the command, replace "SERVICE-NAME" for the name of the service that you want to enable.

How can I see services in CMD?

msc from the command prompt or by opening the start menu, typing "services" from the Start Menu and then launching the Service Manager icon that should show up right away.

How do I open the windows service console?

On your desktop, click Start > Settings > Control Panel to open the Control Panel window. b. Double-click Administrative Tools > Services. The Services console appears.


1 Answers

This won't work. Problem is that you are trying to show UI (Console) from a Windows Service and Windows Service is not running in the context of any particular user. Starting from Vista and later OS Windows Services are running in an isolated session and are disallowed to interact with a user or desktop making it impossible to run.

Depending on what you need there are two solutions to this problem.

  1. If you want the cmd to be opened you might consider using a task scheduled action from Windows Task Scheduler and then perform your actions
  2. If you need just to execute some actions with the cmd.exe, for example copy file, that does not require the UI to be displayed then you can achieve that with the following

Start cmd without creating a window:

ProcessStartInfo processInfo = new ProcessStartInfo
            {
                WindowStyle = ProcessWindowStyle.Normal,
                CreateNoWindow = true,
                UseShellExecute = false,
                FileName = "cmd.exe",
                Arguments = @"/C copy /b Image1.jpg + Archive.rar Image2.jpg"
            };

For the further details please check following links:

  • How can I run an EXE program from a Windows Service using C#?
  • How can a Windows Service start a process when a Timer event is raised?
like image 152
nizzik Avatar answered Oct 17 '22 15:10

nizzik