gpt4 book ai didi

.net - 托管 C++ 中的 ServiceController? (。网)

转载 作者:行者123 更新时间:2023-11-28 08:18:38 24 4
gpt4 key购买 nike

您好,我正在尝试通过 .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)属性”。单击“添加新引用...”按钮并选择适当的引用。或者您可以右键单击该项目并选择“引用...”

enter image description here

关于.net - 托管 C++ 中的 ServiceController? (。网),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6738649/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com