5

Criei um Windows Service de teste, andei pesquisando e vi que para iniciá-lo automaticamente é preciso mudar a propriedade StartType do objeto serviceInstaller para Automatic, que o serviço, depois de instalado, já inicia automaticamente. Entretanto, olhei no Gerenciamento do Computador na parte de Serviços e o Tipo de Inicialização do meu serviço está como Manual. Segue prints abaixo:

SS Serviço no gerenciamento do Computador

SS Configurações do serviceInstaller

Código do ProjectInstaller.cs

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;


namespace servico_teste
{
[RunInstaller(true)]
public partial class ProjectInstaller : System.Configuration.Install.Installer
{
    public ProjectInstaller()
    {
        InitializeComponent();
    }

    private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {
        using (var sc = new ServiceController(serviceInstaller1.ServiceName))
        {
            sc.Start();
        }
    }

    public void ServiceInstaller() 
    {
    //... Installer code here
    this.AfterInstall += new InstallEventHandler(serviceInstaller1_AfterInstall);
    }
}
}

Código do Service1.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.IO;


namespace servico_teste
{
public partial class Service1 : ServiceBase
{
    Timer timer1;

    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        timer1 = new Timer(new TimerCallback(timer1_Tick), null, 15000, 60000);
    }

    protected override void OnStop()
    {
        StreamWriter vWriter = new StreamWriter(@"c:\testeServico.txt", true); 
        vWriter.WriteLine("Servico Parado: " + DateTime.Now.ToString()); 
        vWriter.Flush(); 
        vWriter.Close();

    }

    private void timer1_Tick(object sender) 
    { 
        StreamWriter vWriter = new StreamWriter(@"c:\testeServico.txt", true);
        vWriter.WriteLine("Servico Rodando: " + DateTime.Now.ToString()); 
        vWriter.Flush(); 
        vWriter.Close(); 
    }
}
}

A pergunta é: como faço para que depois de instalado o serviço inicie automaticamente?

2
  • E você não pode mudar o Serviço no gerenciamento do Computador para automático? 15/12/2015 às 14:19
  • Dê uma olhada no tour. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
    – Maniero
    4/03/2016 às 19:47

1 Resposta 1

2

Achei uma resposta no SO.

public ServiceInstaller() {
    //... Installer code here
    this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall);
}

void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e) {
    using (var sc = new ServiceController(serviceInstaller.ServiceName)) {
         sc.Start();
    }
}

Coloquei no GitHub para referência futura.

6
  • Não resolveu, creio que eu esteja fazendo algo de errado. A linha this.AfterInstall += new InstallEventHandler(ServiceInstaller_AfterInstall); na parte do ServiceInstaller_AfterInstall está com o erro: The name 'ServiceInstaller_AfterInstall' does not exist in the current context.Mudei para o nome do meu objeto serviceInstaller1_AfterInstall mas ainda assim o serviço não inicia automaticamente.
    – kaamis
    15/12/2015 às 12:55
  • É para existir, ele está logo abaixo.
    – Maniero
    15/12/2015 às 12:58
  • O problema era o nome mesmo. Contudo o serviço ainda está com o tipo de inicialização manual.
    – kaamis
    15/12/2015 às 13:05
  • Tem algum problema no código, mas como você não postou ele, não tem como ajudar. tela do VS não ajuda nada.
    – Maniero
    15/12/2015 às 13:11
  • Acrescentei os códigos na pergunta @bigown
    – kaamis
    15/12/2015 às 13:40

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .