Windows Service & Windows Application?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tbone

    Windows Service & Windows Application?

    Is there any way to have my C# executable file be runnable as a Windows
    Application AND runnable as a Windows Service? I know I can create a
    separate project for the Windows Service, but I am wondering if there is a
    way to do this with a single executable?


  • Peter Bromberg [C# MVP]

    #2
    Re: Windows Service & Windows Application?

    This is how I do it for running as plain old EXE while debugging. What you
    need would be similar:

    private static void Main(string[] args)
    {
    string opt = null;
    // check for arguments
    if (args.Length 0)
    {
    opt = args[0];
    if (opt != null && opt.ToLower() == "/install")
    {
    TransactedInsta ller ti = new TransactedInsta ller();
    ProjectInstalle r pi = new ProjectInstalle r();
    ti.Installers.A dd(pi);
    String path = String.Format("/assemblypath={0 }",
    Assembly.GetExe cutingAssembly( ).Location);
    String[] cmdline = {path};
    InstallContext ctx = new InstallContext( "", cmdline);
    ti.Context = ctx;
    ti.Install(new Hashtable());
    }
    else if (opt != null && opt.ToLower() == "/uninstall")
    {
    TransactedInsta ller ti = new TransactedInsta ller();
    ProjectInstalle r mi = new ProjectInstalle r();
    ti.Installers.A dd(mi);
    String path = String.Format("/assemblypath={0 }",
    Assembly.GetExe cutingAssembly( ).Location);
    String[] cmdline = {path};
    InstallContext ctx = new InstallContext( "", cmdline);
    ti.Context = ctx;
    ti.Uninstall(nu ll);

    }
    }
    if (opt == null) // e.g. ,nothing on the command line
    {
    #if ( ! DEBUG )
    ServiceBase[] ServicesToRun;
    ServicesToRun = new ServiceBase[] {new Service1()};
    ServiceBase.Run (ServicesToRun) ;


    #else
    // debug code: allows the process to run as a non-service
    // will kick off the service start point, but never kill it
    // shut down the debugger to exit
    Service1 service = new Service1();
    service.OnStart (null);


    Thread.Sleep(Ti meout.Infinite) ;
    #endif

    }

    Comment

    Working...