简体   繁体   English

C# - 从Windows服务运行WPF应用程序

[英]C# - Run WPF application from Windows Service

I have a service, which tracks whether WPF application is running on a computer. 我有一个服务,它跟踪WPF应用程序是否在计算机上运行。 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. 我做了什么,是一个肯定运行WPF应用程序的服务。 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. 我也知道,App.xaml.cs中的构造函数被触发了,因为我在那里创建了一个测试代码,它创建了一个空文件。

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. 我想做的只是打开带有可见窗口的WPF应用程序。

Thanks to @adriano-repetti I found solution how to run WPF application from Windows Service and put it visible on screen. 感谢@ adriano-repetti我找到了如何从Windows服务运行WPF应用程序并将其显示在屏幕上的解决方案。 Solution is here: https://github.com/murrayju/CreateProcessAsUser . 解决方案在这里: https//github.com/murrayju/CreateProcessAsUser This guy did ProcessExtensions static class which starts new proces as a current user. 这个人做了ProcessExtensions静态类,它以当前用户的身份启动新进程。

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. 我设置了3500毫秒,我的应用程序实际上是闪烁的。 After change it to 5000ms, everything was fine. 把它改成5000ms后,一切都很好。

From windows service, You can run console application which launches WPF application. 从Windows服务,您可以运行启动WPF应用程序的控制台应用程序。 It pretty tricky, but should work. 这很棘手,但应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM