2011-07-18 85 views
0

嗨im試圖通過.NET應用程序啓動/停止/禁用Windows服務,但我似乎無法得到下面的代碼工作,它一直說錯誤4錯誤C2065:'ServiceController':未聲明的標識符Managed C++中的ServiceController? (.NET)

這是什麼正確的參考?我似乎無法找到正確的一個在系統::

String ^servicename = "srservice"; 



      // Stop the service if it's started. 

      ServiceController^ controller = new ServiceController(servicename); 
      if (controller.Status == ServiceControllerStatus.Running) 

       controller.Stop(); 



      // Set the startup type of the service. 

      String^ serviceregistrylocation = String::Format("SYSTEM\CurrentControlSet\Services\{0}", servicename); 

      RegistryKey ^localMachine = Registry::LocalMachine; 

      RegistryKey servicekey = localMachine.OpenSubKey(serviceregistrylocation, true); 



      // Set value to 2 for automatic, 3 for manual, or 4 for disabled. 

      servicekey.SetValue("Start", 3);  

行,所以我修改了代碼,它現在編譯,但拋出一個「對象引用不設置到對象的實例」錯誤

    String ^servicename = "Fax"; 



      // Stop the service if it's started. 

      ServiceController^ controller = gcnew ServiceController(servicename); 
      if (controller->Status == ServiceControllerStatus::Running) 

       controller->Stop(); 



      // Set the startup type of the service. 

      String^ serviceregistrylocation = String::Format("SYSTEM\CurrentControlSet\Services\{0}", servicename); 

      RegistryKey ^localMachine = Registry::LocalMachine; 

      RegistryKey ^servicekey = localMachine->OpenSubKey(serviceregistrylocation, true); 



      // Set value to 2 for automatic, 3 for manual, or 4 for disabled. 
      try{ 
      servicekey->SetValue("Start", 4); 
      } 
       catch (Exception^ e) 
     { 
      MessageBox::Show(e->Message); 
     } 

     } 

回答

1

您有使用過關於System::ServiceProcess嗎?如果不是,你將不得不完全符合System::ServiceProcess::ServiceController的資格。此外,您必須包含對System.ServiceProcess.dll程序集的引用。您可以通過從項目的右鍵單擊上下文菜單中選擇「屬性」來添加引用。然後從左側樹形視圖頂部選擇「Common Properties」。點擊「添加新參考...」按鈕並選擇適當的參考。或者,你可以右鍵點擊該項目,並選擇「引用...」

enter image description here

+0

那只是這個問題,我沒有系統:: ServiceProcess :: ServiceController的看來,當它試圖在尋找它System :: serviceProcess不顯示。 – cox

+0

NVM,沒有添加參考,似乎工作,謝謝! – cox

+0

嗯現在即時通訊錯誤說:錯誤錯誤C3673:'Microsoft :: Win32 :: RegistryKey':類沒有複製構造函數 – cox

相關問題