首页 > 解决方案 > Windows 服务无法打开 Windows 窗体

问题描述

我正在尝试创建一个Windows ServiceusingTopShelf并且在此服务中我想启动一个Windows Form.After 我创建了服务并调试了它调用ShowDialog 表单不显示:

服务

 class SimpleServ {
    private Task task;
    private const string PATH = @"D:/out.txt";
    private Logger logger;
    private CancellationTokenSource src = new CancellationTokenSource();
    public SimpleServ() {
        logger = new Logger();

    }
    public void Start() {

        logger.Log("Started");
        this.task = Task.Run(async () => {

            var fm = new Fm(logger);
            while (true) {
                fm.ShowDialog();
                logger.Log("Just closed the dialog");
                await Task.Delay(3000);
            }
        });
    }
    public void Stop() {
        logger.Log("Stopped service");
    }
}

形式

public partial class Fm : Form {
    private Logger log;
    public Fm(Logger log) {
        this.log = log;
        this.log.Log("From Form constructor");
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e) {
        this.log.Log("Button clicked");
        this.Close();
    }
}

主要的

class Program {
        static void Main(string[] args) {
            var exitCode = HostFactory.Run(x => {
                x.Service<SimpleServ>(s => {
                    s.ConstructUsing(h => new SimpleServ());
                    s.WhenStarted(h => h.Start());
                    s.WhenStopped(h => h.Stop());
                });
                x.RunAsLocalSystem();
                x.SetServiceName("SimpleService");
                x.SetDisplayName("Simple Service");
                x.SetDescription("Simple serv description");

            });
            int exitCodeValue = (int)Convert.ChangeType(exitCode, exitCode.GetTypeCode());
            Environment.ExitCode = exitCodeValue;
        }
    }

我已将自己附加到该服务中,并且在它达到ShowDialog什么都没有发生之后。

更新
我还添加了一个Logger来记录所有重要事件,到目前为止,表单似乎打开了,但我看不到它:

记录器

public class Logger {
        private string path;
        public Logger(string logPath=Constants.PATH) {
            this.path = logPath;
        }
        private object @lock = new object();
        public void Log(string message) {
            string formattedMessage = "Date:" + DateTime.Now.ToString() + "\tMessage:" + message;
            File.AppendAllLines(this.path, new string[] { formattedMessage });
        }
    }

该文件的输出是:

Date:6/12/2019 11:19:13 AM  Message:Started
Date:6/12/2019 11:19:13 AM  Message:From Form constructor

标签: winformswindows-servicestopshelf

解决方案


在会话 0 隔离(防止Shatter 攻击的一项重要安全措施)已成为法律的世界中,您应该非常仔细地考虑任何依赖服务交互的设计。

最佳实践是重组您的解决方案,使其具有:

  1. 在后台运行的服务,独立于用户
  2. 与服务交互并可由任何用户运行的传统 GUI 应用程序

推荐阅读