我正在尝试使用Windows窗体应用程序上的按钮单击启动和停止Windows服务,但是当我单击开始按钮时,它会发出以下错误:
Object reference not set to an instance of an object.
这是我的Windows窗体应用程序的源代码
public partial class Form1 : Form
{
string svcStatus;
ServiceController myService;
public Form1()
{
InitializeComponent();
ServiceController myService = new ServiceController();
myService.ServiceName = "ServiceName";
svcStatus = myService.Status.ToString();
}
private void button1_Click(object sender, EventArgs e)
{
if (svcStatus == "Stopped")
{
myService.Start(); // START the service if it is already Stopped
string svcStatusWas = "";
while (svcStatus != "Running")
{
if (svcStatus != svcStatusWas)
{
Console.WriteLine("Status: " + svcStatus);
}
svcStatusWas = svcStatus;
myService.Refresh();
svcStatus = myService.Status.ToString();
}
Console.WriteLine("Service Started!!");
}
}
private void button2_Click(object sender, EventArgs e)
{
if (svcStatus == "Running")
{
myService.Stop(); // STOP the service if it is already Running
string svcStatusWas = "";
while (svcStatus != "Stopped")
{
svcStatusWas = svcStatus;
myService.Refresh();
svcStatus = myService.Status.ToString();
}
Console.WriteLine("Service Stopped!!");
}
}
}
svcStatus我正在停止。请帮助我。
答案 0 :(得分:3)
在Form1()中,您有:
ServiceController myService = new ServiceController();
myService.ServiceName = "ServiceName";
svcStatus = myService.Status.ToString();
声明ServiceController的本地实例。点击处理程序正在使用永远不会被初始化的类成员myService。
将上述三行中的第一行更改为
myService = new ServiceController();
它应该有用。