C# - 从 Windows 服务运行 WPF 应用程序 [英] C# - Run WPF application from Windows Service

查看:57
本文介绍了C# - 从 Windows 服务运行 WPF 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一项服务,可以跟踪 WPF 应用程序是否正在计算机上运行.如果发现此类应用程序已关闭,则它会再次打开它.它是在一个循环中完成的.

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.

我所做的是一项肯定会运行 WPF 应用程序的服务.结果是,我可以在任务资源管理器中看到这个应用程序,但在屏幕上看不到.我也知道,App.xaml.cs 中的构造函数被触发,因为我在那里制作了测试代码,这会创建一个空文件.

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.

这里是服务源代码:

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;
}

我想要做的就是打开带有可见窗口的 WPF 应用程序.

All I want to do, is just open WPF application with visible window.

推荐答案

感谢 @adriano-repetti,我找到了如何从 Windows 服务运行 WPF 应用程序并将其显示在屏幕上的解决方案.解决方案在这里:https://github.com/murrayju/CreateProcessAsUser.这家伙做了 ProcessExtensions 静态类,它以当前用户的身份启动新进程.

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.

我的几句话:如果您在循环中检查进程的状态(活动/非活动),请考虑这种打开应用程序的特殊"方法造成的延迟.与传统方式相比,这真的很耗时.我设置了 3500 毫秒,我的应用程序确实在闪烁.改成5000ms后,一切正常.

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.

这篇关于C# - 从 Windows 服务运行 WPF 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆