3个步骤:
1.安装器代码编写
2.安装器工具类编写
1)安装、启动服务)
2)卸载服务
3.windows服务程序编写(参考:多线程、方便扩展的Windows服务程序框架)
4.代码下载,在文末(注意对照博文看代码)
链接:http://pan.baidu.com/s/1qXH657e 密码:6tw2
1.安装器
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Text; 7 using System.Windows.Forms; 8 using System.IO; 9 using Microsoft.Win32; 10 11 namespace Installutil 12 { 13 public partial class frmInstaller : Form 14 { 15 #region " 成员变量 " 16 private ServiceInstaller _installer; 17 private string svcName = "WuJianService"; 18 private string svcDispName = "WuJianServiceDemo"; 19 #endregion 20 21 #region " 构造函数 " 22 public frmInstaller() 23 { 24 InitializeComponent(); 25 _installer = new ServiceInstaller(); 26 } 27 #endregion 28 29 #region " 安装服务 " 30 private void btnInstall_Click(object sender, EventArgs e) 31 { 32 bool reslut = false; 33 foreach (Control control in this.Controls) 34 { 35 if (control.Controls.Count > 0) 36 { 37 foreach (Control ct in control.Controls) 38 { 39 if (ct.Text.Trim() == "") 40 { 41 MessageBox.Show("请先设置好所有必填设置信息!", "设置未全提示"); 42 return; 43 } 44 } 45 } 46 } 47 48 try 49 { 50 folderBrowserDialog1.Description = "选择安装目录"; 51 folderBrowserDialog1.ShowNewFolderButton = true; 52 folderBrowserDialog1.SelectedPath = "C:\"; 53 DialogResult dr = folderBrowserDialog1.ShowDialog(); 54 if (dr == DialogResult.OK) 55 { 56 string path = folderBrowserDialog1.SelectedPath; 57 if (!Directory.Exists(path)) 58 { 59 Directory.CreateDirectory(path); 60 } 61 //拷出文件 62 File.WriteAllBytes(Path.Combine(path, "WuJian.WindowsServiceDemo.exe"), global::Installutil.Properties.Resources.WuJian_WindowsServiceDemo); 63 reslut = _installer.InstallService(Path.Combine(path, "WuJian.WindowsServiceDemo.exe"), svcName, svcDispName); 64 } 65 } 66 catch (Exception ex) 67 { 68 MessageBox.Show("安装过程发生错误,错误提示:" + ex.Message); 69 } 70 MessageBox.Show(reslut ? "安装成功,请重启计算机使服务生效!" : "安装失败!", reslut ? "成功提示" : "失败提示"); 71 } 72 #endregion 73 74 #region " 卸载服务 " 75 private void btnunInstall_Click(object sender, EventArgs e) 76 { 77 string imagepath = GetImagePath(); 78 if (imagepath != string.Empty) 79 { 80 bool reslut = _installer.UnInstallService(svcName); 81 if (reslut && imagepath != string.Empty) 82 { 83 try 84 { 85 if (File.Exists(imagepath)) 86 { 87 string path = Path.GetDirectoryName(imagepath); 88 DirectoryInfo di = new DirectoryInfo(path); 89 di.Delete(true); 90 } 91 } 92 catch { } 93 } 94 MessageBox.Show(reslut ? "卸载成功,请重启计算机清除服务!" : "卸载失败!", "卸载提示"); 95 } 96 else 97 { 98 MessageBox.Show("当前服务未安装,无需卸载!", "卸载提示"); 99 } 100 } 101 #endregion 102 103 #region " 获取安装目录 " 104 private string GetImagePath() 105 { 106 string result = string.Empty; 107 try 108 { 109 RegistryKey registry = Registry.LocalMachine; 110 RegistryKey key = registry.OpenSubKey(@"SYSTEMControlSet001Services" + svcName); 111 if (null != key) 112 { 113 result = key.GetValue("ImagePath", (object)string.Empty).ToString(); 114 } 115 } 116 catch 117 { } 118 return result; 119 } 120 #endregion 121 } 122 }
2.安装器工具类编写
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.ServiceProcess; namespace Installutil { class ServiceInstaller { #region public Variables private const int SC_MANAGER_CREATE_SERVICE = 0x0002; private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010; private const int SERVICE_DEMAND_START = 0x00000003; private const int SERVICE_ERROR_NORMAL = 0x00000001; private const int STANDARD_RIGHTS_REQUIRED = 0xF0000; private const int SERVICE_QUERY_CONFIG = 0x0001; private const int SERVICE_CHANGE_CONFIG = 0x0002; private const int SERVICE_QUERY_STATUS = 0x0004; private const int SERVICE_ENUMERATE_DEPENDENTS = 0x0008; private const int SERVICE_START = 0x0010; private const int SERVICE_STOP = 0x0020; private const int SERVICE_PAUSE_CONTINUE = 0x0040; private const int SERVICE_INTERROGATE = 0x0080; private const int SERVICE_USER_DEFINED_CONTROL = 0x0100; private const int SERVICE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | SERVICE_QUERY_CONFIG | SERVICE_CHANGE_CONFIG | SERVICE_QUERY_STATUS | SERVICE_ENUMERATE_DEPENDENTS | SERVICE_START | SERVICE_STOP | SERVICE_PAUSE_CONTINUE | SERVICE_INTERROGATE | SERVICE_USER_DEFINED_CONTROL); private const int SERVICE_AUTO_START = 0x00000002; private const int GENERIC_WRITE = 0x40000000; private const int DELETE = 0x10000; #endregion #region DLLImport [DllImport("advapi32.dll")] private static extern IntPtr OpenSCManager(string lpMachineName, string lpSCDB, int scParameter); [DllImport("advapi32.dll")] private static extern IntPtr CreateService(IntPtr SC_HANDLE, string lpSvcName, string lpDisplayName, int dwDesiredAccess, int dwServiceType, int dwStartType, int dwErrorControl, string lpPathName, string lpLoadOrderGroup, int lpdwTagId, string lpDependencies, string lpServiceStartName, string lpPassword); [DllImport("advapi32.dll")] private static extern void CloseServiceHandle(IntPtr SCHANDLE); [DllImport("advapi32.dll")] private static extern int StartService(IntPtr SVHANDLE, int dwNumServiceArgs, string lpServiceArgVectors); [DllImport("advapi32.dll", SetLastError = true)] private static extern IntPtr OpenService(IntPtr SCHANDLE, string lpSvcName, int dwNumServiceArgs); [DllImport("advapi32.dll")] private static extern int DeleteService(IntPtr SVHANDLE); [DllImport("kernel32.dll")] private static extern int GetLastError(); #endregion DLLImport #region " 安装和运行 " /// <summary> /// 安装和运行 /// </summary> /// <param name="svcPath">程序路径.</param> /// <param name="svcName"> 服务名</param> /// <param name="svcDispName">服务显示名称.</param> /// <returns>服务安装是否成功.</returns> public bool InstallService(string svcPath, string svcName, string svcDispName) { try { // 获得服务控制管理器句柄 IntPtr sc_handle = OpenSCManager(null, null, SC_MANAGER_CREATE_SERVICE); if (sc_handle.ToInt32() != 0) { //获得服务句柄 IntPtr sv_handle = CreateService(sc_handle, svcName, svcDispName, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, svcPath,null, 0, null, null, null); if (sv_handle.ToInt32() == 0) { CloseServiceHandle(sc_handle); return false; } else { //试尝启动服务 int i = StartService(sv_handle, 0, null); if (i == 0) { return false; } CloseServiceHandle(sc_handle); return true; } } else { return false; } } catch { return false; } } #endregion #region " 反安装服务 " /// <summary> /// 反安装服务. /// </summary> /// <param name="svcName">服务名</param> /// <returns></returns> public bool UnInstallService(string svcName) { // // 打开SCM管理器 // IntPtr sc_hndl = OpenSCManager(null, null, GENERIC_WRITE); if (sc_hndl.ToInt32() != 0) { // // 打开驱动所对应的服务 // IntPtr svc_hndl = OpenService(sc_hndl, svcName, DELETE); if (svc_hndl.ToInt32() != 0) { int i = DeleteService(svc_hndl); if (i != 0) { // // 关闭驱动所对应的服务 // CloseServiceHandle(sc_hndl); return true; } else { CloseServiceHandle(sc_hndl); return false; } } else { return false; } } else { return false; } } #endregion #region " 判断服务运行 " private bool ServiceIsExisted(string serviceName) { ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController s in services) { if (s.ServiceName == serviceName) { return true; } } return false; } #endregion #region " 启动服务 " public void StartService(string serviceName) { if (ServiceIsExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) { service.Start(); } } else { System.Windows.Forms.MessageBox.Show("找不到服务:" + serviceName + "启动失败", "启动提示"); } } #endregion #region " 停止服务 " public void StopService(string serviceName) { if (ServiceIsExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { service.Stop(); } } else { System.Windows.Forms.MessageBox.Show("找不到服务:" + serviceName + "停止失败", "停止提示"); } } #endregion } }