2014-02-27 35 views
0

我試圖啓動和停止使用Windows窗體應用程序上的按鈕單擊的Windows服務,但只要我點擊開始按鈕,它會給出以下內容錯誤:在按鈕上啓動Windows服務時未將對象引用設置爲對象的實例單擊

Object reference not set to an instance of an object. 

這裏是窗口的我的源代碼形成應用

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我得到stopped.Please幫助我。

+0

在哪一行? – wiero

+0

請顯示一些堆棧跟蹤。 – Crono

+0

@wiero myService.Start(); – Pranav

回答

3

在Form1()你有:

ServiceController myService = new ServiceController(); 
    myService.ServiceName = "ServiceName"; 
    svcStatus = myService.Status.ToString(); 

它聲明的ServiceController的本地實例。點擊處理程序正在使用不會被初始化的類成員myService。

改變上述第一個三行到

myService = new ServiceController(); 

,它應該工作。

+1

+1好... –

相關問題