title: Automatically Stop Windows Service at Uninstall
body: <p>When my service is installed I have a handler that starts the service after it has been installed.</p>
  
  <pre><code>private void InitializeComponent()
  {
      ...
      this.VDMServiceInstaller.AfterInstall += ServiceInstaller_AfterInstall;
  }
  
  
  private void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e)
  {
      ServiceController sc = new ServiceController("MyService");
      sc.Start();
  }
  </code></pre>
  
  <p>I want to stop the service before it is uninstalled so I added an additional handler to InitializeComponent().</p>
  
  <pre><code>this.ServiceInstaller.BeforeUninstall += ServiceInstaller_BeforeUninstall;
  </code></pre>
  
  <p>and added the function:</p>
  
  <pre><code>private void ServiceInstaller_BeforeUninstall(object sender, InstallEventArgs e)
  {
      try
      {
          ServiceController sc = new ServiceController("MyService");
          if (sc.CanStop)
          {
              sc.Stop();
              sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped);
          }
      }
      catch (Exception exception)
      {}
  }
  </code></pre>
  
  <p>But the service doesn't stop before uninstall. Am I using the ServiceController.Stop() function improperly?</p>