zoukankan      html  css  js  c++  java
  • C# Windows 服务

    前两天公司要做一个windows服务,要我提供下。顺手就做了一个壳 现在跟大家分享下:

    1.打开VS(我的是2010),新建一个项目选择“Window 服务” :

    2. 右击 “Service1.cs 设计”  选择 "添加安装程序" :

    3. 在 “Service1.cs 设计”  中 把 ServiceName 设置为 "ServiceTest"(用户可以自己定义),然后 选中serviceInstaller1 把 ServiceName 设置跟之前"Service1.cs 设计"中的一样,还有几个属性设置:

     这些属性的作用就不叙述了,自己去了解。

    接下来 选中 serviceProcessInstaller1 设置属性:

    Ok,现在是写服务的工作了

    右击 在 “Service1.cs 设计”  查看代码,打开如图:

    这个是用户要写自己的逻辑,我这就不叙述了。

    好了,现在服务是写了  该安装了。

    新建一个window Form 程序,我就不贴新建图了 直接看最后的图:

    现在是贴代码了:

            private void btnInstall_Click(object sender, EventArgs e)
            {
                if (!ServiceIsExisted("ServiceTest"))
                {
                    try
                    {
                        string CurrentDirectory = System.Environment.CurrentDirectory;
                        System.Environment.CurrentDirectory = CurrentDirectory + "\Service";
                        ManagedInstallerClass.InstallHelper(new string[] { "WindowsServiceTest.exe" });
                        System.Environment.CurrentDirectory = CurrentDirectory;
                        LabelTooptip.Text = "安装成功!";
                    }
                    catch (Exception ex)
                    {
                        LabelTooptip.Text = "安装出错:" + ex.Message;
                    }
                }
                else
                {
                    LabelTooptip.Text = "该服务已经安装,如需重装请先卸载!";
                
                }
          
            }
    
            private void btnUnInstall_Click(object sender, EventArgs e)
            {
                if (ServiceIsExisted("ServiceTest"))
                {
                    try
                    {
                        string CurrentDirectory = System.Environment.CurrentDirectory;
                        System.Environment.CurrentDirectory = CurrentDirectory + "\Service";
                        ManagedInstallerClass.InstallHelper(new string[] {"/u" ,"WindowsServiceTest.exe" });
                        System.Environment.CurrentDirectory = CurrentDirectory;
                        LabelTooptip.Text = "卸载成功!";
                    }
                    catch (Exception ex)
                    {
                        LabelTooptip.Text = "卸载出错:" + ex.Message;
                    }
                }
                else
                {
                    LabelTooptip.Text = "您要卸载的服务不存在!";
                }
    
    
            }
    
    
    
            private void btnStart_Click(object sender, EventArgs e)
            {
                try
                {
                    ServiceController serviceController = new ServiceController("ServiceTest");
                    serviceController.Start();
                    LabelTooptip.Text = "服务启动成功!";
                }
                catch (Exception ex)
                {
                    LabelTooptip.Text = "服务启动出错:" + ex.Message;
                }
            }
    
            private void btnStop_Click(object sender, EventArgs e)
            {
                try
                {
                    ServiceController serviceController = new ServiceController("ServiceTest");
                    if (serviceController.CanStop)
                        serviceController.Stop();
                    LabelTooptip.Text = "服务停止成功!";
                }
                catch (Exception ex)
                {
                    LabelTooptip.Text = "服务停止出错:" + ex.Message;
                }
    
            }
    
            private bool ServiceIsExisted(string svcName)
            {
                ServiceController[] services = ServiceController.GetServices();
                foreach (ServiceController s in services)
                {
                    if (s.ServiceName == svcName)
                    {
                        return true;
                    }
                }
                return false;
            } 
    

      到这里基本就OK ,但是还有一个问题就是这个程序必须已管理员运行 所以在 Form 程序的 Program.cs 里加上一段代码, 如下代码:

      static void Main()
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                /**
               * 当前用户是管理员的时候,直接启动应用程序
               * 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
               */
                //获得当前登录的Windows用户标示
                System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
                System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
                //判断当前登录用户是否为管理员
                if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                {
                    //如果是管理员,则直接运行
                    Application.Run(new Form1());
                }
                else
                {
                    //创建启动对象
                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                    startInfo.UseShellExecute = true;
                    startInfo.WorkingDirectory = Environment.CurrentDirectory;
                    startInfo.FileName = Application.ExecutablePath;
                    //设置启动动作,确保以管理员身份运行
                    startInfo.Verb = "runas";
                    try
                    {
                        System.Diagnostics.Process.Start(startInfo);
                    }
                    catch
                    {
                        return;
                    }
    
                }
            }

    现在是大功告成了。测试如下:

    在这里我声明下,我也是看了网上的一些人的资料才完成的,当时没有记录人家的网址,在这里先谢谢人家提供的资料。

    如果有问题或者有更好的处理欢迎指点!

    附 源代码:

     http://files.cnblogs.com/files/startlearn/WindowsServiceTest.zip

  • 相关阅读:
    动态表格
    Palindrome Number
    String to Integer (atoi) ???
    Reverse Integer
    Two Sum
    Path Sum
    Minimum Depth of Binary Tree
    Plus One
    Maximum Depth of Binary Tree
    Symmetric Tree
  • 原文地址:https://www.cnblogs.com/startlearn/p/4499521.html
Copyright © 2011-2022 走看看