簡體   English   中英

Windows 窗體應用程序內的 Windows 服務

[英]Windows service inside windows form application

我使用 c# 創建了一個 windows 窗體應用程序。 現在我需要在這個應用程序中添加一個 Windows 服務。 我添加了一個新的 Windows 服務並添加了安裝程序。 我創建了 Windows 安裝程序並將其安裝在 PC 中,但該服務不起作用。 我是 C# 的新手。 請幫我將此服務添加到安裝程序中。

WinForms 應用程序和 Windows 服務項目模板具有不同的引導代碼(請參閱項目中的“Program.cs”文件)。

這個來自 Windows 表單:

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());

這是來自 Windows 服務的:

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
    new Service1()
};
ServiceBase.Run(ServicesToRun);

如果要將這些類型的應用程序組合在一個可執行文件中,則需要稍微修改引導程序代碼:

// we need command line arguments in Main method
[STAThread]
static void Main(string[] args)
{
    if (args.Length > 0 && args[0] == "service")
    {
        // runs service;
        // generated bootstrap code was simplified a little
        ServiceBase.Run(new[]
        {
            new Service1()
        });
    }
    else
    {
        // runs GUI application
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

現在,在安裝服務時,您需要設置命令行參數來運行您的可執行文件: myExe service

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM