C # - launch WPF application from Windows service
I have a service that monitors if a WPF application is running on a computer. If it finds that such an application has been closed, it reopens it. This is done in a loop.
Yes, I know this is bad practice for most users, but there are times when it is necessary.
What I did was a service that most likely starts a WPF application. As a result, I can see this application in the Task Manager, but not on the screen. I also know that the constructor in App.xaml.cs is running because I made some test code there that creates an empty file.
Here's the source code for the service:
private Timer timer;
protected override void OnStart(string[] args)
{
timer = new Timer();
timer.Interval = 3000;
timer.Elapsed += this.Timer_Elapsed;
timer.Enabled = true;
}
private void Timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (!this.CheckIfRunning("Application"))
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.CreateNoWindow = false;
psi.FileName = @"D:\Application.exe";
psi.WindowStyle = ProcessWindowStyle.Normal;
Process proc = new Process();
proc.StartInfo = psi;
proc.Start();
}
}
protected override void OnStop()
{
timer.Enabled = false;
}
All I want to do is just open WPF app with window visible.
source to share
Thanks to @ adriano-repetti, I found a solution how to start a WPF application from Windows Service and put it on the screen. The solution is here: https://github.com/murrayju/CreateProcessAsUser . This guy made a static class ProcessExtensions that starts new processes as the current user.
A few words from me: if you are checking the status of a process (active / inactive) in a loop, consider the latency caused by this "special" approach to opening applications. It really takes a long time compared to the traditional way. I set 3500ms and my app was literally blinking. After changing it to 5000ms everything was fine.
source to share