今天试着用C#编写Windows service. 有几个要求,

第一,可通过参数注册服务

第二,也可通过参数取消注册

第三,可以传递参数给服务

第四,注册成功后,可以弹出窗口进行具体配置

其中第三点,在这里做个备注,传递参数有两种,一种是在Main函数接收参数,一种是在OnStart接收参数

在Main中接收的参数在注册之后,必须要到注册表中进行手工设定,而且这里设定参数不仅Main中可以通过Environment.GetCommandLineArgs()

获得,OnStart函数也可以通过这种方式获得。

OnStart中的参数,只能透过ServiceController.Start()传递,或手工在服务启动窗口中输入,注意,在启动窗口中输入的参数只对本次启动有效,windows是不会记住上次的参数的。若想要在OS启动服务时就带固定的参数,只能通过注册表的方式进行修改。

Parameters you send using ServiceController.Start() method are available to you as parameters to the OnStart() method. If I'm not mistaken (It's been a while since I needed to do this).

The OnStart method's signature is:

OnStart(string[] args)

However, if you need the parameters to be sent to the service each time the service is started (automatically) on boot, then you should look at the MSDN documentation on this. Specifically

Process initialization arguments for  the service in the OnStart method, not  in the Main method. The arguments in  the args parameter array can be set  manually in the properties window for  the service in the Services console.  The arguments entered in the console  are not saved; they are passed to the  service on a one-time basis when the  service is started from the control  panel. Arguments that must be present  when the service is automatically  started can be placed in the ImagePath  string value for the service's  registry key  (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\). You can obtain the arguments  from the registry using the  GetCommandLineArgs method, for  example: string[] imagePathArgs =  Environment.GetCommandLineArgs();.

http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.onstart.aspx

以下代码可以在安装过程中为注册表中写入参数

using System;
using System.ServiceProcess;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Web.Services;
using System.Diagnostics;
using System.IO;
using System.Configuration.Install;
/*
* This is the ProjectInstaller class used to install the project
*/
[RunInstallerAttribute(true)]
publicclass ProjectInstaller: Installer
{
privatestatic Boolean initialized = false;
privatestatic Boolean installing = false;
private ServiceInstaller serviceInstaller;
private ServiceProcessInstaller processInstaller;
private String command;
public ProjectInstaller()
{
BeforeInstall += new InstallEventHandler(BeforeInstallEventHandler);
BeforeUninstall += new InstallEventHandler(BeforeUninstallEventHandler);
}
privatevoid initialize()
{
String username = null;
String password = null;
Console.WriteLine("\n\n---------------------------------------");
Console.WriteLine("Please Enter the name of the Service:\n");
String serviceName = Console.ReadLine();
Console.WriteLine("\nPlease Enter the Service's user account:\n");
username = Console.ReadLine();
Console.WriteLine("\nPlease Enter the user account password\n");
password = Console.ReadLine();
if (installing)
{
Console.WriteLine("\nPlease Enter the command you wish to execute\n");
this.command = Console.ReadLine();
}
Console.WriteLine("\nThanks Dude!\n");
Console.WriteLine("---------------------------------------");
// Instantiate installers for process and services.
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
// The services run under a User Account
processInstaller.Account = ServiceAccount.User;
processInstaller.Username = username;
processInstaller.Password = password;
// The services are started manually.
serviceInstaller.StartType = ServiceStartMode.Manual;
// ServiceName must equal those on ServiceBase derived classes.
serviceInstaller.ServiceName = serviceName;
// Add installers to collection. Order is not important.
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
initialized = true;
}
/*
* Installs the Service but adds a parameters entry
* into the registry under the Service.
*/
publicoverridevoid Install(IDictionary stateServer)
{
Microsoft.Win32.RegistryKey system,
currentControlSet,
services,
service,
config;
try
{
//Let the project installer do its job
base.Install(stateServer);
//Open the HKEY_LOCAL_MACHINE\SYSTEM key
system = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System");
//Open CurrentControlSet
currentControlSet = system.OpenSubKey("CurrentControlSet");
//Go to the services key
services = currentControlSet.OpenSubKey("Services");
//Open the key for your service, and allow writing
service = services.OpenSubKey(this.serviceInstaller.ServiceName, true);
//Add your service's description as a REG_SZ value named "Description"
service.SetValue("Description", this.serviceInstaller.ServiceName + " Description");
//(Optional) Add some custom information your service will use...
config = service.CreateSubKey("Parameters");
config.SetValue("Arguments", command);
Console.WriteLine(service.GetValue("ImagePath"));
string path = service.GetValue("ImagePath") + " " +
this.serviceInstaller.ServiceName;
service.SetValue("ImagePath", path);
}
catch(Exception e)
{
Console.WriteLine("An exception was thrown during service installation:\n" + e.ToString());
}
}
/*
* UnInstalls the Service and removes the parameters entry
* from the registry under the Service.
*/
publicoverridevoid Uninstall(IDictionary stateServer)
{
Microsoft.Win32.RegistryKey system,
currentControlSet,
services,
service;
try
{
//Drill down to the service key and open it with write permission
system = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System");
currentControlSet = system.OpenSubKey("CurrentControlSet");
services = currentControlSet.OpenSubKey("Services");
service = services.OpenSubKey(this.serviceInstaller.ServiceName, true);
//Delete any keys you created during installation (or that your service created)
service.DeleteSubKeyTree("Parameters");
}
catch(Exception e)
{
Console.WriteLine("Exception encountered while uninstalling service:\n" + e.ToString());
}
finally
{
//Let the project installer do its job
base.Uninstall(stateServer);
}
}
privatevoid BeforeInstallEventHandler(object sender, InstallEventArgs e)
{
Console.WriteLine("\nBefore Install");
installing = true;
if (!initialized)
{
initialize();
}
}
privatevoid BeforeUninstallEventHandler(object sender, InstallEventArgs e)
{
Console.WriteLine("\nBefore UnInstall");
installing = false;
if (!initialized)
{
initialize();
}
}
}
/*
* The SISService class used to run executables
*/
class DynService : System.ServiceProcess.ServiceBase
{
private Process process;
public String processName;
public DynService()
{
this.ServiceName = "BOB";
}
publicstaticvoid Main(string [] args)
{
SISService service = new DynService();
if (args.Length != 0)
{
service.ServiceName = args[0];
}
ServiceBase.Run(service);
}
protectedoverridevoid OnStart(string[] args)
{
process = new Process();
process.StartInfo.FileName = ReadArguments();
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
}
///<summary>
/// Stop this service.
///</summary>
protectedoverridevoid OnStop()
{
process.Kill();
}
protectedoverridevoid OnShutdown()
{
process.Kill();
}
protectedoverridevoid OnCustomCommand(int command)
{
if (command == 144)
{
}
}
protected String ReadArguments()
{
Microsoft.Win32.RegistryKey system,
currentControlSet,
services,
service,
param;
//Open the HKEY_LOCAL_MACHINE\SYSTEM key
system = Microsoft.Win32.Registry.LocalMachine.OpenSubKey("System");
//Open CurrentControlSet
currentControlSet = system.OpenSubKey("CurrentControlSet");
//Go to the services key
services = currentControlSet.OpenSubKey("Services");
//Open the key for your service, and allow writing
service = services.OpenSubKey(this.ServiceName, false);
param = service.OpenSubKey("Parameters", false);
String args = (String) param.GetValue("Arguments");
return args;
}
}

下列代码设定服务允许与桌面交互

private void serviceProcessInstaller1_Committed(object sender, InstallEventArgs e)
        {
            try
            {
                ConnectionOptions myConOptions = new ConnectionOptions();
                myConOptions.Impersonation = ImpersonationLevel.Impersonate;
                ManagementScope mgmtScope = new System.Management.ManagementScope(@"root\CIMV2", myConOptions);

mgmtScope.Connect();
                ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + serviceInstaller1.ServiceName + "'");

ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");

InParam["DesktopInteract"] = true;

ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);

}
            catch (Exception err)
            {
                Common.wLog(err.ToString());
            }
        }

转载于:https://www.cnblogs.com/sdikerdong/p/3150042.html

Windows Service开发点滴20130622相关推荐

  1. Visual Studio.net 2010 Windows Service 开发,安装与调试

    本示例完成一个每隔一分钟向C:\log.txt文件写入一条记录为例,讲述一个Windows Service 程序的开发,安装与调试     原程序,加文档示例下载 /Files/zycblog/Sou ...

  2. .net windows service开发与安装

    1.创建一个Windows Service项目名为WindowsServiceTest: 2.添加一个Windows Service项名为TestService.cs: 3.实现TestService ...

  3. .NET开发Windows Service程序 - Topshelf

    在实际项目开发过程中,会经常写一些类似定时检查,应用监控的应用.这类应用在windows平台通常都会写成window service程序. 在百度上搜索一下'c#开发windows service', ...

  4. C#开发Windows Service程序

    Windows Service概念介绍 Windows Service,也称Windows服务,是32位Windows操作系统中一种长期运行的后台程序.它们长期后台运行,没有用户界面,默默无闻,但它们 ...

  5. C# Windows Service服务开发的简单实现(Topshelf)

    概念:(Copyed From 百科) Windows服务是指Windows NT操作系统中的一种运行在后台的计算机程序.它在概念上类似于Unix守护进程.Windows服务必须匹配服务控制管理器(负 ...

  6. Windows Mobile 开发系列文章收藏 - 讨论篇

    关注Windows Mobile 应用开发, 探讨移动应用未来发展方向, 未来的手机又会是一个什么样子呢?  Windows Mobile 未来会发展成何种高度? 这些方面都值得我们去思考关注, 想了 ...

  7. Windows Mobile 开发工具和资源

    经常有朋友想学习 Windows Mobile 开发,体验移动开发的乐趣,但不知道从哪里下载各种开发工具和学习资料.于是我整理了一个列表,里面包含了各个版本的 Windows Mobile SDK, ...

  8. Windows Service:用C#创建Windows Service

    现在的.NET框架已经为Windows service的开发提供足够强大的支持,你只需要关注service所要实现的逻辑,而完全不用关心service底层是如何实现的,相比以前用MFC来说,真是质的飞 ...

  9. 转 Windows Mobile 开发工具和资源 黎波

    经常有朋友想学习 Windows Mobile 开发,体验移动开发的乐趣,但不知道从哪里下载各种开发工具和学习资料.于是我整理了一个列表,里面包含了各个版本的 Windows Mobile SDK, ...

  10. dashboard windows 前端开发环境搭建

    dashboard是kubernetes的云管平台UI界面,正常情况下,其是在linux下开发的,但是,有些特殊情况下,我们也可能希望在windows上搭建起dashboard的开发环境 这里我们将搭 ...

最新文章

  1. 如何学好机器学习数据挖掘?这本《数据分析数学基础》图文并茂带你学习入门...
  2. 绝了!一个妹子 rm -rf 把公司整个数据库删没了
  3. 1138 Postorder Traversal (25 分)【难度: 一般 / 知识点: 建树】
  4. 高内聚,低耦合——8大核心中间件,微服务基础技术栈技术图谱
  5. java上传rar文件_java实现上传zip/rar压缩文件,自动解压
  6. ThreadLocal学习
  7. 网页中加载flash的方法
  8. 夺命雷公狗TP3.2.3商城16-----无限极分类删除(玩法1:有子级分类的不能删除)...
  9. hive 直接访问mysql_hive 直接插入mysql
  10. JDBC——(8)数据库连接池技术的概述
  11. 安装tomcat时出错:failed to install tomcat6 service问题的解决方法
  12. C# 软件开发岗面试经验总结
  13. 设计模式(一) 六大原则
  14. 面试技巧STAR原则
  15. 【数字图像处理】前期准备工作,库的安装(skimage库的安装!)
  16. Mac版excel如何快速进行数据拆分?
  17. 中国高校智能机器人比赛经验总结与分享——1V1擂台机器人
  18. 强化学习系列5:有模型的策略迭代方法
  19. JPEGmini Pro(电脑图片无损压缩工具)官方正式版V3.3.0.0 | 电脑版图片压缩软件免费下载
  20. 广大华软html5期末试卷,广州大学华软软件学院2019年广东录取分数线(2019广大华软工科IT类专业受热捧)...

热门文章

  1. 关于LINUX的NVIDIA显卡驱动安装
  2. 织云Lite发布:详解包管理核心能力
  3. Rize - 一个可以让你简单、优雅地使用 puppeteer 的 Node.js 库
  4. SFB 项目经验-15-配置会议邀请中企业信息
  5. Linux 命令整理-tailf
  6. 『C#基础』C#调用存储过程
  7. Maven插件:maven-javadoc-plugin
  8. Java 8 中的这个接口真好用!炸了!
  9. Spring Boot 如何获取 Controller 方法名和注解信息?
  10. 厉害,刚刚官方宣布 IntelliJ IDEA 2020.2 EAP4发布了!