Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Run WPF application from Windows Service

I have a service, which tracks whether WPF application is running on a computer. If it finds, that such application has been closed, then it openes it again. It's done in a loop.

Yes, I know that this is bad practise for most of users, but there are cases, when it's necessary.

What I did, is a service which for sure runs WPF application. Result is that, I can see this application in Task Explorer, but not on the screen. I also know, that constructor in App.xaml.cs fired, because I made there test code, which creates an empty file.

Here's service source code:

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 application with visible window.

like image 887
Fka Avatar asked Oct 19 '22 05:10

Fka


1 Answers

Thanks to @adriano-repetti I found solution how to run WPF application from Windows Service and put it visible on screen. Solution is here: https://github.com/murrayju/CreateProcessAsUser. This guy did ProcessExtensions static class which starts new proces as a current user.

Few words from me: If you're checking status of a process (active/inactive) in a loop, please take into account lag caused by this "special" approach of opening applications. It's really time consuming in comparision to traditional way. I set 3500 ms and my application was literally blinking. After change it to 5000ms, everything was fine.

like image 61
Fka Avatar answered Oct 22 '22 03:10

Fka