2009-09-25 5 views
28

서비스를 설치하는 프로그램이 있는데 나중에 사용자에게 시작 유형을 "자동"으로 변경하는 옵션을 제공하고 싶습니다..NET (설치 후)에서 Windows 서비스의 시작 유형을 변경하려면 어떻게합니까?

차이점이 있으면 OS는 XP입니다 (Windows API?).

.NET에서 어떻게 할 수 있습니까? 가능한 경우 C#! :) 당신은 또한 설치시 사용자에게 다음이 값을 설정할 수

[RunInstaller(true)] 
public class ProjectInstaller : System.Configuration.Install.Installer 
{ 
    public ProjectInstaller() 
    { 
     ... 
     this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; 
    } 
} 

말을 가지고있는 서비스 설치에서

답변

8

해당 용도로 OpenService() 및 ChangeServiceConfig() 네이티브 Win32 API를 사용할 수 있습니다. pinvoke.net에 관한 정보가 있고 물론 MSDN에 관한 정보가 있다고 생각합니다. P/Invoke Interopt Assistant을 확인하시기 바랍니다.

+6

Downvoter : 설명해 주시면 도움이 될 것입니다. –

9

에게. 또는 Visual Studio 디자이너에서이 속성을 설정하기 만하면됩니다.

+0

아 OK, 그래서 가능한 사후 서비스를 제거하지 않고 설치하지입니까? – joshcomley

+0

해당 설치를 수행 하시겠습니까? 그런 다음 WMI를 사용해야합니다. – Arthur

0
ServiceInstaller myInstaller = new System.ServiceProcess.ServiceInstaller(); 
myInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic; 
2

디자인 화면에서 Service1 구성 요소를 클릭하거나 선택하십시오. 속성에는이 속성을 설정할 수있는 startType 속성이 있습니다.

-2

한 가지 방법은 이전 서비스를 제거하고 C# 응용 프로그램에서 직접 업데이트 된 매개 변수로 새 서비스를 설치하는 것입니다.

앱에 WindowsServiceInstaller이 필요합니다.

[RunInstaller(true)] 
public class WindowsServiceInstaller : Installer 
{ 
    public WindowsServiceInstaller() 
    { 
     ServiceInstaller si = new ServiceInstaller(); 
     si.StartType = ServiceStartMode.Automatic; // get this value from some global variable 
     si.ServiceName = @"YOUR APP"; 
     si.DisplayName = @"YOUR APP"; 
     this.Installers.Add(si); 

     ServiceProcessInstaller spi = new ServiceProcessInstaller(); 
     spi.Account = System.ServiceProcess.ServiceAccount.LocalSystem; 
     spi.Username = null; 
     spi.Password = null; 
     this.Installers.Add(spi); 
    } 
} 

서비스를 다시 설치하려면이 두 줄을 사용하십시오.

ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location }); 
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location }); 
0

당신은 (당신이 사용자가 지정하는 원하기 때문에 당신은 아마 사용자 지정 작업에서이 작업을 수행해야합니다) 당신이 얻을 어떤 값으로 ServiceInstaller.StartType 속성을 설정하여 서비스에 대한 설치 클래스에서 그것을 할 수 있습니다 또는 서비스의 "시작"REG_DWORD 항목을 수정할 수 있습니다. 값 2는 자동이고 3은 수동입니다. 해당 HKEY_LOCAL_MACHINE \ SYSTEM \ Services \ YourServiceName

+0

레지스트리를 수정하면 설치 후 시작 유형을 변경하는 가장 좋은 방법입니다. Microsoft.Win32.Registry 클래스를 사용하여이를 수행 할 수 있습니다. –

+2

그렇게하지 마십시오. 이와 같은 해킹은 최신 Windows 버전에 호환성 톤이있는 이유입니다. 이를 수행 할 수있는 완벽하게 합리적인 API가 있습니다. 관리되지 않는 것입니다. 그러나 당신이 창문에 있다는 것을 알 때 (당신은 두 가지 경우 모두 레지스트리 또는 API/unmanged), 그것은 중요하지 않다. –

+0

어떻게 레지스트리를 해킹을 사용하는 방식으로 사용하고 있습니까? API는 레지스트리, 단지 추상화 계층을 수정합니다 ... – SpaceghostAli

47

P/Invoke를 사용하여 수행하는 방법에 대해 blog post이라고 적었습니다. 내 게시물에서 ServiceHelper 클래스를 사용하여 다음을 수행하여 시작 모드를 변경할 수 있습니다.

var svc = new ServiceController("ServiceNameGoesHere"); 
ServiceHelper.ChangeStartMode(svc, ServiceStartMode.Automatic); 
당신은 모든 서비스를 조회하고 서비스가 바로 StartMode는 속성

   if(service.Properties["Name"].Value.ToString() == userInputValue) 
       { 
        service.Properties["StartMode"].Value = "Automatic"; 
        //service.Properties["StartMode"].Value = "Manual"; 

       } 

를 변경 발견되면 다음 입력 된 사용자 값

에 서비스 이름과 일치하도록 WMI를 사용할 수 있습니다

+0

XP에서 완벽하게 작동합니다! 이 기능은 Windows 7 등에서 작동합니까? – Tom

+0

@Tom Win7에서 테스트 해보지 않았으므로 확실하게 말할 수는 없습니다 ... –

+2

몇 대의 VM에서이 기능을 사용했는데 모든 것이 Win 7에서 제대로 작동하는 것 같습니다. 다시 한 번 감사드립니다. – Tom

5

// 그러면 도메인 컴퓨터에서 실행되는 모든 서비스가 제공되고 "Apple Mobile Device"서비스가 StartMode Automatic으로 변경됩니다. 이 두 기능은 분명히 분리되어야하지만 WMI

내가이 응답을 개선하기 위해 원
private void getServicesForDomainComputer(string computerName) 
    { 
     ConnectionOptions co1 = new ConnectionOptions(); 
     co1.Impersonation = ImpersonationLevel.Impersonate; 
     //this query could also be: ("select * from Win32_Service where name = '" + serviceName + "'"); 
     ManagementScope scope = new ManagementScope(@"\\" + computerName + @"\root\cimv2"); 
     scope.Options = co1; 

     SelectQuery query = new SelectQuery("select * from Win32_Service"); 

     using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query)) 
     { 
      ManagementObjectCollection collection = searcher.Get(); 

      foreach (ManagementObject service in collection) 
      { 
       //the following are all of the available properties 
       //boolean AcceptPause 
       //boolean AcceptStop 
       //string Caption 
       //uint32 CheckPoint 
       //string CreationClassName 
       //string Description 
       //boolean DesktopInteract 
       //string DisplayName 
       //string ErrorControl 
       //uint32 ExitCode; 
       //datetime InstallDate; 
       //string Name 
       //string PathName 
       //uint32 ProcessId 
       //uint32 ServiceSpecificExitCode 
       //string ServiceType 
       //boolean Started 
       //string StartMode 
       //string StartName 
       //string State 
       //string Status 
       //string SystemCreationClassName 
       //string SystemName; 
       //uint32 TagId; 
       //uint32 WaitHint; 
       if(service.Properties["Name"].Value.ToString() == "Apple Mobile Device") 
       { 
        service.Properties["StartMode"].Value = "Automatic"; 

       } 
      } 
     }   
    } 

사용하여 설치 후 서비스 시작 모드를 변경하는 간단 ...한 가지 방법은 서비스 지정 컴퓨터 시작 모드를 변경하려면 :

public void changeServiceStartMode(string hostname, string serviceName, string startMode) 
    { 
     try 
     { 
      ManagementObject classInstance = 
         new ManagementObject(@"\\" + hostname + @"\root\cimv2", 
         "Win32_Service.Name='" + serviceName + "'", 
         null); 

      // Obtain in-parameters for the method 
      ManagementBaseObject inParams = 
       classInstance.GetMethodParameters("ChangeStartMode"); 

      // Add the input parameters. 
      inParams["StartMode"] = startMode; 

      // Execute the method and obtain the return values. 
      ManagementBaseObject outParams = 
       classInstance.InvokeMethod("ChangeStartMode", inParams, null); 

      // List outParams 
      //Console.WriteLine("Out parameters:"); 
      //richTextBox1.AppendText(DateTime.Now.ToString() + ": ReturnValue: " + outParams["ReturnValue"]); 
     } 
     catch (ManagementException err) 
     { 
      //richTextBox1.AppendText(DateTime.Now.ToString() + ": An error occurred while trying to execute the WMI method: " + err.Message); 
     } 
    } 
2

방법 C의 메이크업의 사용에 대해 : \ 창 \ system32를 \ Sc.exe를 그렇게하는 방법?!

VB.NET 코드에서 System.Diagnostics.Process를 사용하여 sc.exe를 호출하여 Windows 서비스의 시작 모드를 변경합니다. 다음은 내 샘플 코드

Public Function SetStartModeToDisabled(ByVal ServiceName As String) As Boolean 
    Dim sbParameter As New StringBuilder 
    With sbParameter 
     .Append("config ") 
     .AppendFormat("""{0}"" ", ServiceName) 
     .Append("start=disabled") 
    End With 

    Dim processStartInfo As ProcessStartInfo = New ProcessStartInfo() 
    Dim scExeFilePath As String = String.Format("{0}\sc.exe", Environment.GetFolderPath(Environment.SpecialFolder.System)) 
    processStartInfo.FileName = scExeFilePath 
    processStartInfo.Arguments = sbParameter.ToString 
    processStartInfo.UseShellExecute = True 

    Dim process As Process = process.Start(processStartInfo) 
    process.WaitForExit() 

    Return process.ExitCode = 0 

최종 기능

관련 문제