C#开发人员能够可视化操作windows服务
使用C#開發(fā)自己的定義windows服務(wù)是一個(gè)很簡(jiǎn)單的事。因此,當(dāng)。我們需要發(fā)展自己windows它的服務(wù)。這是當(dāng)我們需要有定期的計(jì)算機(jī)或運(yùn)行某些程序的時(shí)候,我們開發(fā)。在這里,我有WCF監(jiān)聽案例,因?yàn)槲沂亲霰镜亓奶焓摇1仨歴erver結(jié)束監(jiān)控終端,所以,我開發(fā)了一個(gè)服務(wù)。便控制此監(jiān)聽服務(wù)。
然而。我們開發(fā)的windows服務(wù),默認(rèn)情況下是無法可視化的操作的。這里我就額外的開發(fā)一個(gè)工具來對(duì)此服務(wù)進(jìn)行操作,效果圖例如以下:
開發(fā)步驟:
1、“新建項(xiàng)目”——“Window服務(wù)”
Program.cs代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceProcess;namespace MSMQChatService
{class Program{static void Main(){#region 服務(wù)啟動(dòng)入口。正式用ServiceBase[] ServicesToRun;ServicesToRun = new ServiceBase[] { new MQChatService() };ServiceBase.Run(ServicesToRun);#endregion}}
MQChatService.cs代碼例如以下:
3、切換到MQChatService的可視化界面
4、在可視化界面,單擊鼠標(biāo)右鍵,
將會(huì)出現(xiàn)一個(gè)Installer為后綴的新界面。默認(rèn)好像是Project Installer.cs,我這里將其重命名為ServiceInstaller.cs
分別對(duì)界面上這兩個(gè)組件進(jìn)行屬性配置,詳細(xì)的屬性簽名能夠查看屬性面板的最以下(右下角處)
好了,我們的windows服務(wù)已經(jīng)開發(fā)好了。接下來就開發(fā)一個(gè)可視化的控制器,來控制服務(wù)的安裝、卸載、啟動(dòng)和停止。
1、? 新建一個(gè)windows程序,名稱ServiceSetup。Form1重命名為FrmServiceSetup,
界面控件例如以下:
Program.cs代碼例如以下:
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms;namespace ServiceSetup {static class Program{/// <summary>/// 應(yīng)用程序的主入口點(diǎn)。/// </summary>[STAThread]static void Main(){//獲取欲啟動(dòng)進(jìn)程名string strProcessName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;獲取版本//CommonData.VersionNumber = Application.ProductVersion;//檢查進(jìn)程是否已經(jīng)啟動(dòng),已經(jīng)啟動(dòng)則顯示報(bào)錯(cuò)信息退出程序。??????????? if (System.Diagnostics.Process.GetProcessesByName(strProcessName).Length > 1) ??????????? { ??????????????? MessageBox.Show("程序已經(jīng)執(zhí)行。"); ??????????????? Thread.Sleep(1000); ??????????????? System.Environment.Exit(1); ??????????? } ??????????? else ??????????? { ??????????????? Application.EnableVisualStyles(); ??????????????? Application.SetCompatibleTextRenderingDefault(false); ??????????????? Application.Run(new FrmServiceSetup()); ??????????? } } } }
主界面代碼:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;namespace ServiceSetup {public partial class FrmServiceSetup : Form{string strServiceName = string.Empty;public FrmServiceSetup(){InitializeComponent();strServiceName = string.IsNullOrEmpty(lblServiceName.Text) ? "MSMQChatService" : lblServiceName.Text;InitControlStatus(strServiceName, btnInstallOrUninstall, btnStartOrEnd, btnGetStatus, lblMsg, gbMain);}/// <summary>/// 初始化控件狀態(tài)/// </summary>/// <param name="serviceName">服務(wù)名稱</param>/// <param name="btn1">安裝button</param>/// <param name="btn2">啟動(dòng)button</param>/// <param name="btn3">獲取狀態(tài)button</param>/// <param name="txt">提示信息</param>/// <param name="gb">服務(wù)所在組合框</param>void InitControlStatus(string serviceName, Button btn1, Button btn2, Button btn3, Label txt, GroupBox gb){try{btn1.Enabled = true;if (ServiceAPI.isServiceIsExisted(serviceName)){btn3.Enabled = true;btn2.Enabled = true;btn1.Text = "卸載服務(wù)";int status = ServiceAPI.GetServiceStatus(serviceName);if (status == 4){btn2.Text = "停止服務(wù)";}else{btn2.Text = "啟動(dòng)服務(wù)";}GetServiceStatus(serviceName, txt);//獲取服務(wù)版本號(hào)string temp = string.IsNullOrEmpty(ServiceAPI.GetServiceVersion(serviceName)) ? string.Empty : "(" + ServiceAPI.GetServiceVersion(serviceName) + ")";gb.Text += temp;}else{btn1.Text = "安裝服務(wù)";btn2.Enabled = false;btn3.Enabled = false;txt.Text = "服務(wù)【" + serviceName + "】未安裝!";}}catch (Exception ex){txt.Text = "error";LogAPI.WriteLog(ex.Message);}}/// <summary>/// 安裝或卸載服務(wù)/// </summary>/// <param name="serviceName">服務(wù)名稱</param>/// <param name="btnSet">安裝、卸載</param>/// <param name="btnOn">啟動(dòng)、停止</param>/// <param name="txtMsg">提示信息</param>/// <param name="gb">組合框</param>void SetServerce(string serviceName, Button btnSet, Button btnOn, Button btnShow, Label txtMsg, GroupBox gb){try{string location = System.Reflection.Assembly.GetExecutingAssembly().Location;string serviceFileName = location.Substring(0, location.LastIndexOf('\\')) + "\\" + serviceName + ".exe";if (btnSet.Text == "安裝服務(wù)"){ServiceAPI.InstallmyService(null, serviceFileName);if (ServiceAPI.isServiceIsExisted(serviceName)){txtMsg.Text = "服務(wù)【" + serviceName + "】成功安裝!";btnOn.Enabled = btnShow.Enabled = true;string temp = string.IsNullOrEmpty(ServiceAPI.GetServiceVersion(serviceName)) ?string.Empty : "(" + ServiceAPI.GetServiceVersion(serviceName) + ")"; gb.Text += temp; btnSet.Text = "卸載服務(wù)"; btnOn.Text = "啟動(dòng)服務(wù)"; } else { txtMsg.Text = "服務(wù)【" + serviceName + "】安裝失敗,請(qǐng)檢查日志。"; } } else { ServiceAPI.UnInstallmyService(serviceFileName); if (!ServiceAPI.isServiceIsExisted(serviceName)) { txtMsg.Text = "服務(wù)【" + serviceName + "】卸載成功!"; btnOn.Enabled = btnShow.Enabled = false; btnSet.Text = "安裝服務(wù)"; //gb.Text =strServiceName; } else { txtMsg.Text = "服務(wù)【" + serviceName + "】卸載失敗。請(qǐng)檢查日志!"; } } } catch (Exception ex) { txtMsg.Text = "error"; LogAPI.WriteLog(ex.Message); } } //獲取服務(wù)狀態(tài) void GetServiceStatus(string serviceName, Label txtStatus) { try { if (ServiceAPI.isServiceIsExisted(serviceName)) { string statusStr = ""; int status = ServiceAPI.GetServiceStatus(serviceName); switch (status) { case 1: statusStr = "服務(wù)未執(zhí)行!
"; break; case 2: statusStr = "服務(wù)正在啟動(dòng)!"; break; case 3: statusStr = "服務(wù)正在停止!
"; break; case 4: statusStr = "服務(wù)正在執(zhí)行。"; break; case 5: statusStr = "服務(wù)即將繼續(xù)。"; break; case 6: statusStr = "服務(wù)即將暫停!"; break; case 7: statusStr = "服務(wù)已暫停!
"; break; default: statusStr = "未知狀態(tài)!"; break; } txtStatus.Text = statusStr; } else { txtStatus.Text = "服務(wù)【" + serviceName + "】未安裝!"; } } catch (Exception ex) { txtStatus.Text = "error"; LogAPI.WriteLog(ex.Message); } } //啟動(dòng)服務(wù) void OnService(string serviceName, Button btn, Label txt) { try { if (btn.Text == "啟動(dòng)服務(wù)") { ServiceAPI.RunService(serviceName); int status = ServiceAPI.GetServiceStatus(serviceName); if (status == 2 || status == 4 || status == 5) { txt.Text = "服務(wù)【" + serviceName + "】啟動(dòng)成功!"; btn.Text = "停止服務(wù)"; } else { txt.Text = "服務(wù)【" + serviceName + "】啟動(dòng)失敗!"; } } else { ServiceAPI.StopService(serviceName); int status = ServiceAPI.GetServiceStatus(serviceName); if (status == 1 || status == 3 || status == 6 || status == 7) { txt.Text = "服務(wù)【" + serviceName + "】停止成功!"; btn.Text = "啟動(dòng)服務(wù)"; } else { txt.Text = "服務(wù)【" + serviceName + "】停止失敗。"; } } } catch (Exception ex) { txt.Text = "error"; LogAPI.WriteLog(ex.Message); } } //安裝or卸載服務(wù) private void btnInstallOrUninstall_Click(object sender, EventArgs e) { btnInstallOrUninstall.Enabled = false; SetServerce(strServiceName, btnInstallOrUninstall, btnStartOrEnd, btnGetStatus, lblMsg, gbMain); btnInstallOrUninstall.Enabled = true; btnInstallOrUninstall.Focus(); } //啟動(dòng)or停止服務(wù) private void btnStartOrEnd_Click(object sender, EventArgs e) { btnStartOrEnd.Enabled = false; OnService(strServiceName, btnStartOrEnd, lblMsg); btnStartOrEnd.Enabled = true; btnStartOrEnd.Focus(); } //獲取服務(wù)狀態(tài) private void btnGetStatus_Click(object sender, EventArgs e) { btnGetStatus.Enabled = false; GetServiceStatus(strServiceName, lblMsg); btnGetStatus.Enabled = true; btnGetStatus.Focus(); } private void FrmServiceSetup_Resize(object sender, EventArgs e) { if (this.WindowState == FormWindowState.Minimized) //最小化到系統(tǒng)托盤 { notifyIcon1.Visible = true; //顯示托盤圖標(biāo) this.ShowInTaskbar = false; this.Hide(); //隱藏窗口 } } private void FrmServiceSetup_FormClosing(object sender, FormClosingEventArgs e) { DialogResult result = MessageBox.Show("是縮小到托盤?", "確認(rèn)", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information); if (result== DialogResult.Yes) { // 取消關(guān)閉窗口 e.Cancel = true; // 將窗口變?yōu)樽钚』?this.WindowState = FormWindowState.Minimized; } else if (result == DialogResult.No) { System.Environment.Exit(0); } else { e.Cancel = true; } } private void notifyIcon1_MouseClick(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left&&this.WindowState == FormWindowState.Minimized) { this.Show(); this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; //顯示在系統(tǒng)任務(wù)欄 //notifyIcon1.Visible = false; //托盤圖標(biāo)不可見 this.Activate(); } } private void 打開主界面ToolStripMenuItem_Click(object sender, EventArgs e) { this.Show(); this.WindowState = FormWindowState.Normal; this.ShowInTaskbar = true; //顯示在系統(tǒng)任務(wù)欄 notifyIcon1.Visible = false; //托盤圖標(biāo)不可見 this.Activate(); } private void 退出ToolStripMenuItem_Click(object sender, EventArgs e) { System.Environment.Exit(0); ExitProcess(); } ??? //結(jié)束進(jìn)程 ??????? private void ExitProcess() ??????? { ??????????? System.Environment.Exit(0); ??????????? Process[] ps = Process.GetProcesses(); ??????????? foreach (Process item in ps) ??????????? { ??????????????? if (item.ProcessName == "ServiceSetup") ??????????????? { ??????????????????? item.Kill(); ??????????????? } ??????????? } ??????? } ?} }
新建一個(gè)類,專門用于日志操作LogAPI.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks;namespace ServiceSetup {public class LogAPI{private static string myPath = "";private static string myName = "";/// <summary>/// 初始化日志文件/// </summary>/// <param name="logPath"></param>/// <param name="logName"></param>public static void InitLogAPI(string logPath, string logName){myPath = logPath;myName = logName;}/// <summary>/// 寫入日志/// </summary>/// <param name="ex">日志信息</param>public static void WriteLog(string ex){if (myPath == "" || myName == "")return;string Year = DateTime.Now.Year.ToString();string Month = DateTime.Now.Month.ToString().PadLeft(2, '0');string Day = DateTime.Now.Day.ToString().PadLeft(2, '0');//年月日文件夾是否存在,不存在則建立if (!Directory.Exists(myPath + "\\LogFiles\\" + Year + "_" + Month + "\\" + Year + "_" + Month + "_" + Day)){Directory.CreateDirectory(myPath + "\\LogFiles\\" + Year + "_" + Month + "\\" + Year + "_" + Month + "_" + Day);}//寫入日志UNDO,Exception has not been handlestring LogFile = myPath + "\\LogFiles\\" + Year + "_" + Month + "\\" + Year + "_" + Month + "_" + Day + "\\" + myName;if (!File.Exists(LogFile)){System.IO.StreamWriter myFile;myFile = System.IO.File.AppendText(LogFile);myFile.Close();}while (true){try{StreamWriter sr = File.AppendText(LogFile);sr.WriteLine(DateTime.Now.ToString("HH:mm:ss") + " " + ex);sr.Close();break;}catch (Exception e){System.Threading.Thread.Sleep(50);continue;}}}} } Windows服務(wù)的操作類ServiceAPI.csusing System; using System.Collections; using System.Collections.Generic; using System.Configuration.Install; using System.IO; using System.Linq; using System.Reflection; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using Microsoft.Win32;namespace ServiceSetup {public class ServiceAPI{/// <summary>/// 檢查服務(wù)存在的存在性/// </summary>/// <param name=" NameService ">服務(wù)名</param>/// <returns>存在返回 true,否則返回 false;</returns>public static bool isServiceIsExisted(string NameService){ServiceController[] services = ServiceController.GetServices();foreach (ServiceController s in services){if (s.ServiceName.ToLower() == NameService.ToLower()){return true;}}return false;}/// <summary>/// 安裝Windows服務(wù)/// </summary>/// <param name="stateSaver">集合</param>/// <param name="filepath">程序文件路徑</param>public static void InstallmyService(IDictionary stateSaver, string filepath){AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();AssemblyInstaller1.UseNewContext = true;AssemblyInstaller1.Path = filepath;AssemblyInstaller1.Install(stateSaver);AssemblyInstaller1.Commit(stateSaver);AssemblyInstaller1.Dispose();}/// <summary>/// 卸載Windows服務(wù)/// </summary>/// <param name="filepath">程序文件路徑</param>public static void UnInstallmyService(string filepath){AssemblyInstaller AssemblyInstaller1 = new AssemblyInstaller();AssemblyInstaller1.UseNewContext = true;AssemblyInstaller1.Path = filepath;AssemblyInstaller1.Uninstall(null);AssemblyInstaller1.Dispose();}/// <summary>/// 啟動(dòng)服務(wù)/// </summary>/// <param name=" NameService ">服務(wù)名</param>/// <returns>存在返回 true,否則返回 false;</returns>public static bool RunService(string NameService){bool bo = true;try{ServiceController sc = new ServiceController(NameService);if (sc.Status.Equals(ServiceControllerStatus.Stopped) || sc.Status.Equals(ServiceControllerStatus.StopPending)){sc.Start();}}catch (Exception ex){bo = false;LogAPI.WriteLog(ex.Message);}return bo;}/// <summary>/// 停止服務(wù)/// </summary>/// <param name=" NameService ">服務(wù)名</param>/// <returns>存在返回 true,否則返回 false;</returns>public static bool StopService(string NameService){bool bo = true;try{ServiceController sc = new ServiceController(NameService);if (!sc.Status.Equals(ServiceControllerStatus.Stopped)){sc.Stop();}}catch (Exception ex){bo = false;LogAPI.WriteLog(ex.Message);}return bo;}/// <summary>/// 獲取服務(wù)狀態(tài)/// </summary>/// <param name=" NameService ">服務(wù)名</param>/// <returns>返回服務(wù)狀態(tài)</returns>public static int GetServiceStatus(string NameService){int ret = 0;try{ServiceController sc = new ServiceController(NameService);ret = Convert.ToInt16(sc.Status);}catch (Exception ex){ret = 0;LogAPI.WriteLog(ex.Message);}return ret;}/// <summary>/// 獲取服務(wù)安裝路徑/// </summary>/// <param name="ServiceName"></param>/// <returns></returns>public static string GetWindowsServiceInstallPath(string ServiceName){string path = "";try{string key = @"SYSTEM\CurrentControlSet\Services\" + ServiceName;path = Registry.LocalMachine.OpenSubKey(key).GetValue("ImagePath").ToString();path = path.Replace("\"", string.Empty);//替換掉雙引號(hào) FileInfo fi = new FileInfo(path);path = fi.Directory.ToString();}catch (Exception ex){path = "";LogAPI.WriteLog(ex.Message);}return path;}/// <summary>/// 獲取指定服務(wù)的版本/// </summary>/// <param name="serviceName">服務(wù)名稱</param>/// <returns></returns>public static string GetServiceVersion(string serviceName){if (string.IsNullOrEmpty(serviceName)){return string.Empty;}try{string path = GetWindowsServiceInstallPath(serviceName) + "\\" + serviceName + ".exe";Assembly assembly = Assembly.LoadFile(path);AssemblyName assemblyName = assembly.GetName();Version version = assemblyName.Version;return version.ToString();}catch (Exception ex){LogAPI.WriteLog(ex.Message);return string.Empty;}}} } 注意:記住服務(wù)程序dll復(fù)制到可視化的安裝程序bin下面的文件夾。版權(quán)聲明:本文博客原創(chuàng)文章,博客,未經(jīng)同意,不得轉(zhuǎn)載。
總結(jié)
以上是生活随笔為你收集整理的C#开发人员能够可视化操作windows服务的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mysql学习笔记(六)增删改查
- 下一篇: 利用联合双边滤波或引导滤波进行升采样(U