0

This is supposed to be simple but I don't understand why it's not working. I'm trying to run a batch file (that runs a console application) from a .NET 6.0 Windows Service with this content:

@echo off
cd "C:\MyFolder"
MyExecutable.exe
pause

and I have this code:

var command = "\"C:\\Users\\Administrator\\Desktop\\mybatchfile.bat\"";
ProcessStartInfo start = new()
{
    FileName = "cmd.exe",
    Arguments = $"/c {command}",
    UseShellExecute = false,
    CreateNoWindow = false,
    ErrorDialog = false,
    RedirectStandardError = false,
    RedirectStandardOutput = false,
    WindowStyle = ProcessWindowStyle.Normal
};
Process.Start(start);

What's happening is that my console application (MyExecutable.exe) is executed, yet I do not see the Command window for it. It's launched in the background despite CreateNoWindow set to false and WindowStyle set to ProcessWindowStyle.Normal.

Mark Cilia Vincenti
  • 1,410
  • 8
  • 25
  • It's probably because of the @echo off in the script itself which prevents the script from writing to the console window – TheEvilMetal Sep 06 '22 at 09:44
  • I tried taking off the `@echo off` but I had the same result. – Mark Cilia Vincenti Sep 06 '22 at 09:44
  • 3
    Windows services run in a non-interactive desktop session and cannot interact with the user (by design, as a security boundary). The usual workaround is to either have an auto-startup user application that communicates with the service through IPC, or to rethink the design if a service isn't really what's needed (for example, a scheduled task that interacts with the desktop is another option). – Jeroen Mostert Sep 06 '22 at 09:45
  • Ah yes, that must be it, you're absolutely right. I'm trying to run a watchdog service for a console application though; is there no hack for this? – Mark Cilia Vincenti Sep 06 '22 at 09:47
  • 2
    No. Pre-Vista there was a flag to allow services to do this anyway, but it has since been removed and the separation is now absolute. Either don't use a service, don't use user interaction, or use two processes, the service and whatever has to interact with the user. Things like kiosk mode (to run a specific application only and heavily restrict user interaction otherwise) are another option. – Jeroen Mostert Sep 06 '22 at 09:50
  • Technically speaking, what a service can still do is find the desktop session of the currently logged-on user (assuming there is just one) and start a process there, as discussed [in this question](https://stackoverflow.com/q/4278373/4137916). But this is quite difficult and it's likely some of the solutions there don't work (without adaptation) for .NET 6. I'd go for one of the other approaches. – Jeroen Mostert Sep 06 '22 at 09:53

0 Answers0