0

I have compilled a service in Visual C# 2010. If I click on BService.exe it starts but also show a messagebox: "Cannot start service from the command line or a debugger. A Windows Service must be installed (using installutil.exe) and then started with ServerExplorer, Windows Services Administrative tool or the NET START command." if I click OK program closes. If I install if with C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\installutil.exe, and start from services.msc it also starts but doesn't show MessageBox.Show("sdas"), so doesn't work. How to install/run the service?

public partial class BService : ServiceBase
{
    private System.Timers.Timer timer;
    public BService()
    {
        timer = new System.Timers.Timer(2000);
        timer.Enabled = true;
        timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
        InitializeComponent();
    }
    public void Start() { timer.Start();}
    public void Stop() { timer.Stop();}
    protected override void OnStart(string[] args) { this.Start();}
    protected override void OnStop() { this.Stop();}

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        MessageBox.Show("sdas");
    }
}
  • 2
    _"Doesn't show message box so doesn't work"_ - that is wrong. Services aren't supposed to interact with the desktop. There is a messagebox somewhere, you just can't see it. – CodeCaster May 06 '14 at 10:43
  • `InitializeComponent()`? Why are you using a forms application as service? – Nyerguds May 06 '14 at 12:20

2 Answers2

0

Use below code to install windows service using C#:

public void InstallWinService(string winServicePath)
{
    try
    {
        ManagedInstallerClass.InstallHelper(new string[] { winServicePath});
    }
    catch (Exception)
    {

        throw;
    }
}

Use below code to run win Server using C#

public void StartService(string serviceName)
{
    ServiceController service = new ServiceController(serviceName);
    try
    {
        service.MachineName = "localhost";
        service.Start();
        service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 1, 0));
    }
    catch (Exception ex)
    {
        throw ex;
    }
}
Mahsh Nikam
  • 63
  • 2
  • 9
0

Windows services are no longer (from Vista onwards) allowed to show UI to the user, no Forms, no MessageBoxes, no Console Windows, no .Net Framework update dialogues... nothing. You can't get round this and if you could Microsoft would patch your method so it wouldn't work for long. Here's the chapter and verse on the subject.

Change your code so that it logs events and look in the Event Viewer instead (see Using EventLog in ClickOnce application).

Community
  • 1
  • 1
RAM
  • 475
  • 1
  • 3
  • 14