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

标签 .net c++ managed

您好,我正在尝试通过 .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/

相关文章:

c# - 在 C# 中屏幕抓取大型机屏幕*无需*第 3 方实用程序

visual-studio - 如何使Visual Studios构建系统了解托管dll的非托管依赖关系?

c# - 如何发送带有html附件的邮件

c# - 为什么我的 DbProviderFactory 的执行方式与 SqlClientFactory 不同?

.net - ASP + 限制子页面使用 css 文件

c# - .NET 多个 gmail 帐户与 2 个网络浏览器控件

c++ - 如何在运行时将字符串转换为代码

c++ - Trie 数据结构实现的 bug

c++ - 循环遍历struct元素

c# - PInvokeStackimBalance 在签名正常时一直被检测到