2011-07-18 43 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

相关问题