RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1010599
Accepted
nick_n_a
nick_n_a
Asked:2020-08-06 14:53:15 +0000 UTC2020-08-06 14:53:15 +0000 UTC 2020-08-06 14:53:15 +0000 UTC

如何在一个 C# 中创建一个服务?

  • 772

如何在单个可执行文件中创建完整的服务?有一个现成的应用程序(你可以采取零winforms)。我添加了 services.cs,没有任何效果,没有例外。

ManagedInstallerClass.InstallHelper - 读取 - 失败。试图通过 RunInstaller 安装 - 也不起作用。

我尝试通过 sc create 安装(在命令行上) - 它已安装。

Services.cs 文本

using System;
using System.ServiceProcess;
using System.Configuration.Install;
using System.Collections;
using System.Collections.Specialized;
using System.Windows.Forms;


namespace CaiNiaoServiceWinForms{


class Service:ServiceBase  {

 static string  myname = "AMyService";

 public Service()
        {
            this.ServiceName = myname;
            this.CanStop = true;
            this.CanPauseAndContinue = false;
            this.AutoLog = true;
        }

  static public void Run() {
        ServiceBase[] ServicesToRun = new ServiceBase[] { new Service() };
        ServiceBase.Run(ServicesToRun);
     }

  protected override void OnStart(string[] args){ // TODO: add startup stuff
        }

        protected override void OnStop(){
           // TODO: add shutdown stuff
        }

//---------------------------------      
// Service config for UI          
// тут работает
  static ServiceController GetService() {
     foreach (ServiceController item in  ServiceController.GetServices())
            if (item.ServiceName == myname) return item;
     return null;
     }


  public static bool Installed {
        get { // тут работает
          return (GetService()!=null);
          }

        set { // тут не работает
           string  servicePath = System.Reflection.Assembly.GetEntryAssembly().Location;
           if (value) { /*install*/
MyInstaller inst = new MyInstaller();
//inst.Install(dict); не работает, даже если создать словарь
//inst.Commit(dict);
              } 
              //ManagedInstallerClass.InstallHelper(new[] { "/i" , servicePath, "/SERVICE" });

              //ManagedInstallerClass.InstallHelper(new[] { servicePath , "/SERVICE" });
             }  else { /*uninstall*/
              ManagedInstallerClass.InstallHelper(new[] { "/u" , servicePath, "/SERVICE" });
             }


            }
      }


  public static void DoStart () {
      if (Installed) GetService().Start();
      }


  public static void DoStop () {
      if (Installed) GetService().Stop();
      }




  }
//------------------

  [System.ComponentModel.RunInstaller(true)]
  public partial class MyInstaller: Installer { 
    // https://docs.microsoft.com/ru-ru/dotnet/api/system.serviceprocess.serviceinstaller
    private ServiceInstaller serviceInstaller;
    private ServiceProcessInstaller processInstaller;     


      public MyInstaller() {
         processInstaller = new ServiceProcessInstaller();
         serviceInstaller = new ServiceInstaller();
         processInstaller.Account = ServiceAccount.LocalSystem;
         serviceInstaller.StartType = ServiceStartMode.Manual;
         serviceInstaller.Context  = 
            new System.Configuration.Install.InstallContext(null, new string[]{"/SERVICE"});
         }

      }           
}

我的主要(program.cs)

static void Main(string[] args)
{
   try {

    if (args.Length > 0) {
      if (args[0]  == "/SERVICE") {
            Service.Run();
            return;
            }

      if (args[0].ToUpper()  == "/INSTALL") { 
          Service.Installed = true; 
          return;
          }
      if (args[0].ToUpper()  == "/UNINSTALL") {
          Service.Installed = false;
          return;
          }
      }
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    Application.Run(new MainForm(args));
    } catch (Exception e) {
      MessageBox.Show(e.ToString());
      }
}
c#
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    nick_n_a
    2020-08-06T19:20:52Z2020-08-06T19:20:52Z

    启动服务... 根据微软的说法,要启动服务,必须使用特殊工具或其特殊实用程序手动完成(使用 InstallHelper 等时)。我使用 WMI 安装。

    PS 要安装启动服务,程序必须从管理员(包括管理单元)下启动。

    服务的“模板”变成了这样

    using System;
    using System.ServiceProcess;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Windows.Forms;
    using System.Threading;
    using System.Management;
    
    
    
    
    
    public partial class Service:ServiceBase  {
    
     static string  myname = "CMyService";
    
     public Service()
            {
                this.ServiceName = myname;
                this.CanStop = true;
                this.CanPauseAndContinue = false;
            }
    
    
      static public bool Run() {
            ServiceBase[] ServicesToRun = new ServiceBase[] { new Service() };
            ServiceBase.Run(ServicesToRun);
            return true;
         }
    
    
      static private volatile bool _Working;
      static private volatile bool _Worked;
    
      static public bool Working {  get {  return _Working; }} 
    
    
    
      static void MyThread(){
            while (_Working){
                 Worker.current.Work();
                }
            _Worked = true;
            }
    
    
    
      protected override void OnStart(string[] args)
            {
             _Working = true;
             _Worked = false;
             (new Thread(new ThreadStart(MyThread))).Start();
            }
    
            protected override void OnStop()
            {
              _Working = false;
              while (!_Worked) Thread.Sleep(1000);    
            }
    
      //-----------------------------------------------------------
      // Service config for UI
      static ServiceController GetService() {
         foreach (ServiceController item in  ServiceController.GetServices())
                if (item.ServiceName == myname) return item;
         return null;
         }
    
    
    
      public static bool Installed {
            get { return (GetService()!=null);}
    
            set {
               int q = 0;
               string  servicePath = System.Reflection.Assembly.GetEntryAssembly().Location;
    
               //ManagementObject serv =  new ManagementObject(new ManagementScope(@"root\CIMV2"),new ManagementPath( "Win32_Service"),null);
               ManagementScope sc = new ManagementScope("root\\CIMV2");
               sc.Connect();
    
    
               if (value) { /*install*/
    
                  ManagementObject serv = new ManagementClass(sc, new ManagementPath("Win32_Service"),null);
                  q =Convert.ToInt32( serv.InvokeMethod("Create",new object[] 
                   { myname, myname,  servicePath /*+" /SERVICE" /**/,  16/*own*/, 0, "Manual", 0 , ".\\LocalSystem", "", null }));                            
                 }  else { /*uninstall*/
                   foreach(ManagementObject item in (new ManagementObjectSearcher(sc,new ObjectQuery("select * from Win32_Service"))).Get()){
                     if (item["Name"].ToString() == myname)
                        q =Convert.ToInt32( item.InvokeMethod("Delete",null));                    
                     }
    
                 }
                string[]  errors = {null, "The request is not supported" ,"Access denied","The service cannot be stopped because other services that are running are dependent on it",
                     "The requested control code is not valid, or it is unacceptable to the service","The requested control code cannot be sent to the service because the state of the service 0,1,2",
                      "The service has not been started","The service did not respond to the start request in a timely fashion",
                      "Unknown failure when starting the service","path was not found",
                       "The service is already running","The database to add a new service is locked.",
                       "A dependency this service relies on has been removed from the system",
                       "The service failed to find the service needed from a dependent service",
                        "The service has been disabled from the system","The service does not have the correct authentication to run on the system.",
                     "This service is being removed from the system.","The service has no execution thread.","The service has circular dependencies when it starts.",
                      "A service is running under the same name.","The service name has invalid characters.","Invalid parameters have been passed to the service.",
                    "The account under which this service runs is either invalid or lacks the permissions to run the service.",
                      "The service exists in the database of services available from the system.", "The service is currently paused in the system."};
                if (q != 0) MessageBox.Show(q > 24? q.ToString():errors[q]);
                }
          }
    
    
    
    
      public static void DoStart () {
          if (Installed) GetService().Start();
          }
    
    
      public static void DoStop () {
          if (Installed) GetService().Stop();
          }
    
      }
    

    程序的文本是

        static void Main(string[] args)
        {
         int q = 0;
        try {
          q = System.Diagnostics.Process.GetCurrentProcess().SessionId;
         } catch {};
         if ((q == 0)?Service.Run() : false) return;
         if (args.Length > 0) {            
              if (args[0].ToUpper()  == "/INSTALL") { Service.Installed = true;return;}
              if (args[0].ToUpper()  == "/UNINSTALL"){Service.Installed = false;return;}
              }
         Application.EnableVisualStyles();
         Application.SetCompatibleTextRenderingDefault(false);
         Application.Run(new MainForm(args));
        }
    
    • 0

相关问题

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    根据浏览器窗口的大小调整背景图案的大小

    • 2 个回答
  • Marko Smith

    理解for循环的执行逻辑

    • 1 个回答
  • Marko Smith

    复制动态数组时出错(C++)

    • 1 个回答
  • Marko Smith

    Or and If,elif,else 构造[重复]

    • 1 个回答
  • Marko Smith

    如何构建支持 x64 的 APK

    • 1 个回答
  • Marko Smith

    如何使按钮的输入宽度?

    • 2 个回答
  • Marko Smith

    如何显示对象变量的名称?

    • 3 个回答
  • Marko Smith

    如何循环一个函数?

    • 1 个回答
  • Marko Smith

    LOWORD 宏有什么作用?

    • 2 个回答
  • Marko Smith

    从字符串的开头删除直到并包括一个字符

    • 2 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5