关于服务程序开发的内容这里就不写了,网上一搜一大堆,这里只对一些细节问题作一些整理,方便查找。
1、程序安装和卸载服务(不用在Cmd 里面用InstallUtil.exe来安装的方法)

private void btn_install_Click(object sender, EventArgs e)
        {
            if (!flag)
            {
                lab_msg.Text = "请先选择正确的服务安装程序!";
            }
            else
            {
                if (!ServiceIsExisted(svcname))
                {
                    string[] args = { filepath };
                    ServiceController sCtr = new ServiceController(svcname);

                    try
                    {
                        ManagedInstallerClass.InstallHelper(args);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("安装失败,请重试!");
                        return;
                    }
                    MessageBox.Show("安装成功!");
                   // Application.Exit();

                }
                else
                {
                    MessageBox.Show("已经安装了该服务,请勿重复安装!");
                    return;
                }
               
            }
        }
 private bool ServiceIsExisted(string svcName)
         {
             ServiceController[] services = ServiceController.GetServices();
             foreach (ServiceController s in services)
             {
                 if (s.ServiceName == svcName)
                 {
                     return true;
                 }
             }
             return false;
        }
//卸载
        private void btn_delete_Click(object sender, EventArgs e)
        {
            try
            {
                string[] cmdline = { };

                TransactedInstaller transactedInstaller = new TransactedInstaller();
                AssemblyInstaller assemblyInstaller = new AssemblyInstaller(filepath, cmdline);
                transactedInstaller.Installers.Add(assemblyInstaller);
                transactedInstaller.Uninstall(null);
                
                MessageBox.Show("卸载成功");
                //Application.Exit();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
        }

2、安装服务时去除需要输入用户名和密码
在设计窗口中选择ProcessInstall控件,将其Account属性设计为LocalSystem即可。
3、添加服务的描述
同上设计窗口中选择serviceInstall控件,其Discription中的内容即为服务描述,后面的DisplayName为显示的服务名称。
4、服务在启动后又自动停止了*****相关的错误
通过查看“管理工具->事件查看器”中的信息可以看出服务在什么地方停止了,为什么停止了,方便调试。
01-16 00:01