如何在C#中创建可以使用GUI *或*作为Windows服务运行的Windows应用程序?

时间:2009-02-20 00:49:05

标签: c# windows-services

我想使用C#创建一个应用程序......:

  • 可以作为Windows应用程序运行,具有GUI(它将指示进度,状态等)

    或者

  • 可以作为Windows服务运行,无需GUI

有可能吗?有人可以让我开始吗?

我想替代方案是我可以创建一个Windows服务,然后是一个单独的GUI应用程序,它可以轮询Windows服务以从中获取数据(进度,状态等)。

在这种情况下......如何从我的GUI应用程序中获取Windows服务中的数据?

5 个答案:

答案 0 :(得分:6)

我正在做一些类似于你所要求的事情。我已对其进行了编程,以便在将命令行参数“/ form”发送到可执行文件时,它将弹出一个Windows窗体,而不是作为服务运行。

就运行后台作业本身而言,在这两种情况下,您都需要执行某种线程(可能带有计时器)来执行工作并将状态异步报告回表单。这将是关于创建线程GUI应用程序的完全不同的讨论主题。

“表单或服务”代码如下所示:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    private static void Main(string[] args)
    {
        if (args.Length > 0 && args[0] == "/form")
        {
            var form = new MainForm();
            Application.Run(form);
            return;
        }

        var ServicesToRun = new ServiceBase[]
            {
                new BackgroundService()
            };

        ServiceBase.Run(ServicesToRun);
    }
}

答案 1 :(得分:2)

我从未做过可以作为Windows服务或GUI运行的应用程序,但我们有很多应用程序可以使用编译器标志在控制台应用程序和Windows服务之间切换。 (我刚看到cmd line arg的答案 - 甚至可能更好!)

我们通常只使用编译器标志在两者之间切换。这是一个例子......我没有完全想到这一点,但它可能会给你一个开始:

#define RUN_AS_SERVICE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.ServiceProcess;

namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
#if RUN_AS_SERVICE

            System.ServiceProcess.ServiceBase[] ServicesToRun;
            ServicesToRun = new System.ServiceProcess.ServiceBase[]
            {
                new MyService()
            };
            System.ServiceProcess.ServiceBase.Run(ServicesToRun);
#else
            // Run as GUI
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
#endif
        }
    }
    public class MyService : ServiceBase
    {
        protected override void OnStart(string[] args)
        {
            // Start your service
        }

        protected override void OnStop()
        {
            // Stop your service
        }
    }
}

答案 2 :(得分:2)

在库中构建实际应用程序。然后,您可以添加任何UI(我说松散,因为服务不是真正的UI)。只要您将应用程序视为Windows应用程序和服务应用程序,您就可以开发两个应用程序。如果您认为应用程序是它解决的业务问题,那么您将会想到Windows窗体UI和服务UI,它可以满足您的需求。

虽然这听起来很清醒,但您会惊讶地发现有多少应用程序需要完全覆盖才能成为不同的UI类型。感谢你的提问。它使我确信我需要写这本书。 : - )

答案 3 :(得分:1)

你应该选择后者。创建您的服务,然后创建一个单独的GUI应用程序。在框架中已经为您提供了大部分用于完成所有这些操作的管道。看一下ServiceController类。

答案 4 :(得分:0)

我看到了这个帖子,它可能会为你提供更多信息

How to write c# service that I can also run as a winforms program?