//获取服务状态 private void GetServiceStatus(string serviceName, Label lblMsg) { try { if (ServiceAPI.IsExist(serviceName)) { string statusStr = ""; int status = ServiceAPI.GetServiceStatus(serviceName); switch (status) { case 1: statusStr = "服务未运行!"; break; case 2: statusStr = "服务正在启动!"; break; case 3: statusStr = "服务正在停止!"; break; case 4: statusStr = "服务正在运行!"; break; case 5: statusStr = "服务即将继续!"; break; case 6: statusStr = "服务即将暂停!"; break; case 7: statusStr = "服务已暂停!"; break; default: statusStr = "未知状态!"; break; } lblMsg.Text = statusStr; } else { lblMsg.Text = "服务【" + serviceName + "】未安装!"; } } catch (Exception ex) { lblMsg.Text = "error" + ex.Message;; } }
//启动服务 private void OnService(string serviceName, Button btn, Label txt) { try { if (btn.Text == "启动服务") { ServiceAPI.RunService(serviceName); int status = ServiceAPI.GetServiceStatus(serviceName); if (status == 2 || status == 4 || status == 5) { txt.Text = "服务【" + serviceName + "】启动成功!"; btn.Text = "停止服务"; } else { txt.Text = "服务【" + serviceName + "】启动失败!"; } } else { ServiceAPI.StopService(serviceName); int status = ServiceAPI.GetServiceStatus(serviceName); if (status == 1 || status == 3 || status == 6 || status == 7) { txt.Text = "服务【" + serviceName + "】停止成功!"; btn.Text = "启动服务"; } else { txt.Text = "服务【" + serviceName + "】停止失败!"; } } } catch (Exception ex) { txt.Text = "error" + ex.Message;; } }
/// <summary> /// 初始化控件状态 /// </summary> /// <param name="serviceName">服务名称</param> /// <param name="lblMsg">信息显示</param> /// <param name="gb">控件内容组合框</param> /// <param name="btn1">安装按钮</param> /// <param name="btn2">启动按钮</param> /// <param name="btn3">获取状态按钮</param> private void InitControlStatus(string serviceName, Label lblMsg, GroupBox gb, Button btn1, Button btn2, Button btn3) { try { btn1.Enabled = true; if (ServiceAPI.IsExist(serviceName)) { btn3.Enabled = true; btn2.Enabled = true; btn1.Text = "卸载服务"; int status = ServiceAPI.GetServiceStatus(serviceName); if (status == 4) { btn2.Text = "停止服务"; } else { btn2.Text = "启动服务"; } this.GetServiceStatus(serviceName, lblMsg); //获取服务版本 string temp = string.IsNullOrEmpty(ServiceAPI.GetServiceVersion(serviceName)) ? string.Empty : "(" + ServiceAPI.GetServiceVersion(serviceName) + ")"; gb.Text += temp; } else { btn2.Enabled = false; btn3.Enabled = false; } } catch (Exception ex) { lblMsg.Text = "Error" + ex.Message; } }