重要:必须右键管理员权限运行程序,否则无法正常安装Windows服务
界面:
使用ManagedInstallerClass安装和卸载服务,使用ServiceController启动和停止服务,代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UIWinformTest
{
public partial class WindowsServiceInstall : Form
{
string[] argsInstall = new string[] { Path.Combine(Environment.CurrentDirectory, @"service\WindowsService1.exe") };
string[] argsUninstall = new string[] { "/u", Path.Combine(Environment.CurrentDirectory, @"service\WindowsService1.exe") };
ServiceController serviceController;
static readonly string serviceName = "Service1";
public WindowsServiceInstall()
{
InitializeComponent();
}
private void btnInstallService_Click(object sender, EventArgs e)
{
try
{
ManagedInstallerClass.InstallHelper(argsInstall);
MessageBox.Show("服务安装成功");
}
catch(Exception ex)
{
MessageBox.Show("服务安装失败!\r\n" + ex.ToString());
}
}
private void btnUninstallService_Click(object sender, EventArgs e)
{
try
{
ManagedInstallerClass.InstallHelper(argsUninstall);
MessageBox.Show("服务卸载成功");
}
catch (Exception ex)
{
MessageBox.Show("服务卸载失败!\r\n" + ex.ToString());
}
}
private void btnStartService_Click(object sender, EventArgs e)
{
try
{
serviceController = new ServiceController(serviceName);
if (serviceController.Status != ServiceControllerStatus.Running && serviceController.Status != ServiceControllerStatus.StartPending)
{
serviceController.Start();
serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(30));
MessageBox.Show("服务启动成功");
}
}
catch (Exception ex)
{
MessageBox.Show("服务启动失败: " + ex.Message);
}
}
private void btnStopService_Click(object sender, EventArgs e)
{
try
{
serviceController = new ServiceController(serviceName);
if (serviceController.Status != ServiceControllerStatus.Stopped && serviceController.Status != ServiceControllerStatus.StopPending)
{
serviceController.Stop();
serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(30));
MessageBox.Show("服务停止成功");
}
}
catch (Exception ex)
{
MessageBox.Show("服务停止失败: " + ex.Message);
}
}
}
}