您好,我正在尝试通过 .NET 应用程序启动/停止/禁用 Windows 服务,但我似乎无法让下面的代码正常工作,它一直说错误 4 error C2065: 'ServiceController' : undeclared identifier
正确的引用是什么?我似乎无法在 System::
中找到正确的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 );
}
}
最佳答案
System::ServiceProcess
有 using 语句吗?否则,您必须使用 System::ServiceProcess::ServiceController
完全限定该类。此外,您还必须包含对 System.ServiceProcess.dll 程序集的引用。您可以通过从项目的右键单击上下文菜单中选择属性来添加引用。然后从左侧 TreeView 的顶部选择“公共(public)属性”。单击“添加新引用...”按钮并选择适当的引用。或者您可以右键单击该项目并选择“引用...”
关于.net - 托管 C++ 中的 ServiceController? (。网),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6738649/