ServiceController in Managed c++? (.NET)
Hi im trying to start/stop/disable windows services via a .NET app but I cant seem to get the below code to work, it keeps saying that Error 4 error C2065: 'ServiceController' : undeclared identifier
What is the correct reference for this? I cant seem to find the correct one in 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);
Ok so i modified the code and it now compiles but thro开发者_开发百科ws an "object reference not set to an instance of an object" error
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 );
}
}
Do you have a using statement for System::ServiceProcess
? If not you'll have to fully qualify the class with System::ServiceProcess::ServiceController
. Also, you have to include a reference to the System.ServiceProcess.dll assembly. You can add a reference by selecting Properties from the right click context menu on your project. Then select "Common Properties" from the top of the tree view on the left hand side. Click the "Add New Reference..." button and select the appropriate reference. Or you can right click on the project and select "References..."
精彩评论