using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Windows.Forms;
namespace ProductManager
{
public partial class FormService : Form
{
#region 自定义对象
private readonly Stopwatch stopWatch;
private readonly ServiceController dbService;
#endregion
public FormService()
{
#region
InitializeComponent();
stopWatch = new Stopwatch();
dbService = DBConnection.Service;
txtServiceName.Text = dbService.ServiceName;
txtMachineName.Text = Environment.MachineName;
#endregion
}
#region Service.Refresh
private void timerStatus_Tick(object sender, EventArgs e)
{
dbService.Refresh(); // 通过将属性重置为其当前值来刷新属性值。
switch (dbService.Status)
{
case ServiceControllerStatus.Running:
stopWatch.Stop();
btnStart.Enabled = false;
btnPause.Enabled = dbService.CanPauseAndContinue;
btnStop.Enabled = dbService.CanStop;
btnPause.Text = "&Pause";
break;
case ServiceControllerStatus.Paused:
stopWatch.Stop();
btnStart.Enabled = false;
btnPause.Enabled = true;
btnStop.Enabled = false;
btnPause.Text = "&Continue";
break;
case ServiceControllerStatus.Stopped:
stopWatch.Stop();
btnStart.Enabled = true;
btnPause.Enabled = false;
btnStop.Enabled = false;
break;
}
labelStatus.Text = string.Format("Status:{0}", dbService.Status);
labelTime.Text = string.Format("in {0:#,##0} ms", stopWatch.ElapsedMilliseconds);
}
#endregion
#region Service.Start
private void btnStart_Click(object sender, EventArgs e)
{
dbService.Refresh();
if (dbService.Status != ServiceControllerStatus.Stopped) // 服务已停止。
return;
try
{
stopWatch.Reset();
stopWatch.Start();
dbService.Start(); // 启动该服务(在运行里输入 net start ServiceName)。
}
catch
{
return;
}
}
#endregion
#region Service.PauseAndContinue
private void btnPause_Click(object sender, EventArgs e)
{
try
{
stopWatch.Reset();
stopWatch.Start();
dbService.Refresh();
switch (dbService.Status)
{
case ServiceControllerStatus.Running: // 服务正在运行。
dbService.Pause(); // 暂停该服务(在运行里输入 net pause ServiceName)。
break;
case ServiceControllerStatus.Paused: // 服务已暂停。
dbService.Continue(); // 继续该服务(在运行里输入 net continue ServiceName)。
break;
}
}
catch
{
return;
}
}
#endregion
#region Service.Stop
private void btnStop_Click(object sender, EventArgs e)
{
dbService.Refresh();
if (dbService.Status != ServiceControllerStatus.Running)
return;
try
{
stopWatch.Reset();
stopWatch.Start();
dbService.Stop(); // 停止该服务(在运行里输入 net stop ServiceName)。
}
catch
{
return;
}
}
#endregion
#region ProcessTabKey
private void textBox_Click(object sender, EventArgs e)
{
this.ProcessTabKey(true); // 选择下一个可用控件并使其成为活动控件。
}
#endregion
}
}