这篇文章主要介绍“C#如何启动Windows服务的窗体程序”,在日常操作中,相信很多人在C#如何启动Windows服务的窗体程序问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C#如何启动Windows服务的窗体程序”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
C#启动Windows服务的窗体程序的由来:最近应客户的要求,做了一个定时监控WINDOWS服务的程序,要做到随机启动,定时监控指定的服务,如果没有开启则开启,由于时间仓促,没有经过长时间的服务器端运行,现将思路及代码公布,以后有改进会及时更新:
一、C#启动Windows服务的窗体程序思路:
本程序的核心在于随机启动和WINDOWS服务上,对于随机启动,引入Microsoft.Win32命名空间,利用RegistryKey类即可完成对注册表的增、删、改等操作;对于WINDOWS服务,引入System.ServiceProcess命名空间,利用ServiceController类即可完成对系统服务的启动、停止、查询等操作。改日就测试程序的稳定性及资源消耗率等指标。
二、C#启动Windows服务的窗体程序代码如下,这里程序默认为开启MSSQLSERVER服务,并添加了托盘区图标,可以在启动时或启动后最小化到托盘区:
using System; //C#启动Windows服务的窗体程序using System.Drawing; using System.Collections; using System.ComponentModel; using System.windows.Forms; using System.Data; using System.ServiceProcess; using System.IO; using Microsoft.Win32; namespace WatchService { /// ﹤summary﹥ /// Form1 的摘要说明,C#启动Windows服务的窗体程序 /// ﹤/summary﹥ public class WatchService : System.windows.Forms.Form { private System.windows.Forms.Button btn_startWatch; private System.windows.Forms.Button btn_stopWatch; private System.windows.Forms.Button btn_startReg; private System.windows.Forms.Button btn_stopReg; private System.windows.Forms.Label lbl_appStatus; private System.windows.Forms.TextBox tbx_serviceName; private System.windows.Forms.Button btn_Exit; private System.windows.Forms.TextBox tbx_interval; private System.windows.Forms.Timer timer1; private System.windows.Forms.NotifyIcon notifyIcon1; private System.ComponentModel.IContainer components; public WatchService() { // C#启动Windows服务的窗体程序 // windows 窗体设计器支持所必需的 // InitializeComponent(); // // TODO: 在 InitializeComponent //调用后添加任何构造函数代码 // } /// ﹤summary﹥///C#启动Windows服务的窗体程序 /// 清理所有正在使用的资源。 /// ﹤/summary﹥ protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region windows 窗体设计器生成的代码 /// ﹤summary﹥ /// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 /// ﹤/summary﹥ private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(WatchService)); this.btn_startWatch = new System.windows.Forms.Button(); this.btn_stopWatch = new System.windows.Forms.Button(); this.btn_startReg = new System.windows.Forms.Button(); this.btn_stopReg = new System.windows.Forms.Button(); this.lbl_appStatus = new System.windows.Forms.Label(); this.tbx_serviceName = new System.windows.Forms.TextBox(); this.btn_Exit = new System.windows.Forms.Button(); this.tbx_interval = new System.windows.Forms.TextBox(); this.timer1 = new System.windows.Forms.Timer(this.components); this.notifyIcon1 = new System.windows.Forms.NotifyIcon(this.components); this.SuspendLayout(); // // btn_startWatch // C#启动Windows服务的窗体程序this.btn_startWatch.Location = new System.Drawing.Point(112, 8); this.btn_startWatch.Name = "btn_startWatch"; this.btn_startWatch.Size = new System.Drawing.Size(64, 23); this.btn_startWatch.TabIndex = 0; this.btn_startWatch.Text = "开始监控"; this.btn_startWatch.Click += new System.EventHandler(this.btn_startWatch_Click); // // btn_stopWatch // this.btn_stopWatch.Location = new System.Drawing.Point(184, 8); this.btn_stopWatch.Name = "btn_stopWatch"; this.btn_stopWatch.Size = new System.Drawing.Size(64, 23); this.btn_stopWatch.TabIndex = 1; this.btn_stopWatch.Text = "停止监控"; // // btn_startReg // C#启动Windows服务的窗体程序this.btn_startReg.Location = new System.Drawing.Point(112, 40); this.btn_startReg.Name = "btn_startReg"; this.btn_startReg.Size = new System.Drawing.Size(88, 24); this.btn_startReg.TabIndex = 2; this.btn_startReg.Text = "开启随机启动"; this.btn_startReg.Click += new System.EventHandler(this.btn_startReg_Click); // // btn_stopReg // this.btn_stopReg.Location = new System.Drawing.Point(232, 40); this.btn_stopReg.Name = "btn_stopReg"; this.btn_stopReg.Size = new System.Drawing.Size(88, 24); this.btn_stopReg.TabIndex = 3; this.btn_stopReg.Text = "关闭随机启动"; this.btn_stopReg.Click += new System.EventHandler(this.btn_stopReg_Click); // // lbl_appStatus // C#启动Windows服务的窗体程序this.lbl_appStatus.ForeColor = System.Drawing.Color.Red; this.lbl_appStatus.Location = new System.Drawing.Point(16, 72); this.lbl_appStatus.Name = "lbl_appStatus"; this.lbl_appStatus.Size = new System.Drawing.Size(304, 23); this.lbl_appStatus.TabIndex = 4; this.lbl_appStatus.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // tbx_serviceName // this.tbx_serviceName.BorderStyle = System.windows.Forms.BorderStyle.FixedSingle; this.tbx_serviceName.ForeColor = System.Drawing.Color.Red; this.tbx_serviceName.Location = new System.Drawing.Point(8, 8); this.tbx_serviceName.Name = "tbx_serviceName"; this.tbx_serviceName.TabIndex = 5; this.tbx_serviceName.Text = "输入服务名"; this.tbx_serviceName.MouseDown += new System.windows.Forms.MouseEventHandler( this.tbx_serviceName_MouseDown); // // btn_Exit // this.btn_Exit.Location = new System.Drawing.Point(256, 8); this.btn_Exit.Name = "btn_Exit"; this.btn_Exit.Size = new System.Drawing.Size(64, 23); this.btn_Exit.TabIndex = 6; this.btn_Exit.Text = "退出程序"; this.btn_Exit.Click += new System.EventHandler(this.btn_Exit_Click); // // tbx_interval // C#启动Windows服务的窗体程序this.tbx_interval.BorderStyle = System.windows.Forms.BorderStyle.FixedSingle; this.tbx_interval.ForeColor = System.Drawing.Color.Red; this.tbx_interval.Location = new System. Drawing.Point(8, 40); this.tbx_interval.Name = "tbx_interval"; this.tbx_interval.TabIndex = 7; this.tbx_interval.Text = "输入监控间隔(秒)"; this.tbx_interval.MouseDown += new System.windows.Forms.MouseEventHandler( this.tbx_interval_MouseDown); // // timer1 // this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // notifyIcon1 // this.notifyIcon1.Icon = ((System.Drawing.Icon) (resources.GetObject("notifyIcon1.Icon"))); this.notifyIcon1.Text = "双击打开WatchService"; this.notifyIcon1.Visible = true; this.notifyIcon1.DoubleClick += new System.EventHandler(this.notifyIcon1_DoubleClick); // // WatchService // C#启动Windows服务的窗体程序this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(328, 102); this.Controls.Add(this.tbx_interval); this.Controls.Add(this.btn_Exit); this.Controls.Add(this.tbx_serviceName); this.Controls.Add(this.lbl_appStatus); this.Controls.Add(this.btn_stopReg); this.Controls.Add(this.btn_startReg); this.Controls.Add(this.btn_stopWatch); this.Controls.Add(this.btn_startWatch); this.MaximizeBox = false; this.Name = "WatchService"; this.ShowInTaskbar = false; this.Text = "WatchService"; this.windowstate = System.windows. Forms.Formwindowstate.Minimized; this.Resize += new System.EventHandler( this.WatchService_Resize); this.Load += new System.EventHandler( this.WatchService_Load); this.ResumeLayout(false); } #endregion private ServiceController scDBService; private string serviceName="MSSqlServer"; // 默认服务名 private int iInterval=60; // 默认监控间隔(秒) /// ﹤summary﹥ ///C#启动Windows服务的窗体程序/// 应用程序的主入口点。 /// ﹤/summary﹥ [STAThread] static void Main() { Application.Run(new WatchService()); } // 开启监控 private void btn_startWatch_Click( object sender, System.EventArgs e) { if(this.tbx_serviceName.Text=="") { this.lbl_appStatus.Text="服务名不能为空"; this.tbx_serviceName.Focus(); return; } if(this.tbx_interval.Text=="") { this.lbl_appStatus.Text="服务监控间隔不能为空"; this.tbx_interval.Focus(); return; } serviceName=this.tbx_serviceName.Text; iInterval=int.Parse(this.tbx_interval.Text); this.timer1.Interval=iInterval*1000; startService(); } // 开启随机启动 private void btn_startReg_Click( object sender, System.EventArgs e) { try { string dir=Directory.GetCurrentDirectory(); dir+="\\WatchService.exe"; RegistryKey akey=Registry.LocalMachine; akey=akey.OpenSubKey(@"SOFTWARE\Microsoft \windows\CurrentVersion\Run",true); akey.SetValue("WatchService",dir); akey.Close(); this.lbl_appStatus.Text="开启随机启动成功。"; } catch(Exception exp) { this.lbl_appStatus.Text="开启随机启动失败, 原因:"+exp.Message; } } //C#启动Windows服务的窗体程序private void tbx_serviceName_MouseDown( object sender, System.windows.Forms.MouseEventArgs e) { this.tbx_serviceName.Text=""; } // 关闭随机启动 private void btn_stopReg_Click(object sender, System.EventArgs e) { try { RegistryKey akey=Registry.LocalMachine; akey=akey.OpenSubKey(@"SOFTWARE\Microsoft \windows\CurrentVersion\Run",true); akey.SetValue("WatchService",false); akey.Close(); this.lbl_appStatus.Text="关闭随机启动成功。"; } catch(Exception exp) { this.lbl_appStatus.Text="关闭随机启动失败,原因:"+exp.Message; } } private void btn_Exit_Click(object sender, System.EventArgs e) { Application.Exit(); } /// ﹤summary﹥ /// 开启指定的windows服务 ///C#启动Windows服务的窗体程序/// ﹤/summary﹥ private void startService() { try { scDBService=new ServiceController(serviceName); ServiceController[] scAllService= ServiceController.GetServices(); int i=0; while(i﹤scAllService.Length) { if(scAllService[i].DisplayName==serviceName) { if(scDBService.Status.Equals(ServiceControllerStatus.Stopped)) { this.lbl_appStatus.Text=serviceName+" 服务正在启动……"; scDBService.Start(); } else if(scDBService.Status.Equals( ServiceControllerStatus.Running)) { this.lbl_appStatus.Text=serviceName+" 服务正在运行……"; } if(!this.timer1.Enabled) this.timer1.Start(); return; } else { i++; } } this.lbl_appStatus.Text=serviceName+" 服务并没有安装在本机上,请检查。"; if(this.timer1.Enabled) this.timer1.Stop(); } catch(Exception exp) { this.lbl_appStatus.Text=serviceName+ "服务启动失败,原因:"+exp.Message; } } // 监控时钟 private void timer1_Tick(object sender, System.EventArgs e) { startService(); } private void tbx_interval_MouseDown(object sender, System.windows.Forms.MouseEventArgs e) { this.tbx_interval.Text=""; } // 窗体加载后即最小化到托盘区 private void WatchService_Load( object sender, System.EventArgs e) { this.Hide(); this.notifyIcon1.Visible=true; startService(); } // 窗体最小化 private void WatchService_Resize( object sender, System.EventArgs e) { if (this.windowstate==Formwindowstate.Minimized) { this.Hide(); this.notifyIcon1.Visible=true; } } // 托盘区图标操作 private void notifyIcon1_DoubleClick( object sender, System.EventArgs e) { this.Visible = true; this.windowstate = Formwindowstate.Normal; this.notifyIcon1.Visible = false; } // 停止监控 private void btn_stopWatch_Click( object sender, System.EventArgs e) { this.timer1.Stop(); } } }
到此,关于“C#如何启动Windows服务的窗体程序”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注编程网网站,小编会继续努力为大家带来更多实用的文章!