Search code examples
c#windowswinformsvisual-studio-2015startup

How To Run App.exe On Windows Startup Before Login? (Execute WinForm Before Login & Show Executed Form After Login For Interact = Show GUI)


I have a winform application (.exe file) in my windows server 2008 VPS.
This app should grab some data from internet every 5 minutes and save them to a text file.
My VPS restarts after 2 or 3 days for no reason.
I want to force my server run that application on startup & execute it in every reboot.
For this purpose i followed this instruction :

It is simple. The process is.

  1. Run gpedit.msc
  2. Go to computer Configuration -> Windows Setting -> Scripts(Startup/shutdown)
  3. Go to Startup properties then you will get the new windows.
  4. Now add the program that you want to run before login.

The problem is that file is executed on startup, but after login to windows i can not see it's form is running.
I can see that app is running in task manager.
How can i see that winform after login to windows?(I need GUI)
I mean my application must be running even before log in and it should sit on System Tray from which I can "show" Interface for interact.
If there is a way in c# programming for show that app after login please share.


Solution

  • You need to separate the services of your application from UI.

    • The service could be a Windows Service or a console application which runs before startup.
    • The UI could be a Windows Forms Application which runs after user login.
    • To communicate between the service and the windows Application, you can use an IPC solution, like self-hosted WCF or self-hosted Web API.

    GUI application + WCF Service hosted in Windows Service + Installer

    Here I'll share a step by step by step example including:

    • A Windows Service
    • A WCF Service hosted in Windows Service
    • A WinForms application which calls methods of the WCF service
    • An installer which installs windows service and the WinForms application and put the application in startup.

    As a result, after installation the service will be started in windows startup. The GUI application also will start when user logs into the application. Then if you click on a button it will show a message from service.

    Clone or Download:

    ServiceLayer Project

    1. Create a class library project (ServiceLayer)

    2. Add a new WCF service to the class library. (MyWCFService)

    3. Modify the contract:

      [ServiceContract]
      public interface IMyWCFService
      {
          [OperationContract]
          string Echo(string message);
      }
      
    4. Modify the implementation of MyWCFService:

      public class MyWCFService : IMyWCFService
      {
          public string Echo(string message)
          {
              return message;
          }
      }
      
    5. Add a Windows Service. (MyWindowsService)

    6. Modify the implementation of the service:

      partial class MyWindowsService : ServiceBase
      {
          ServiceHost host;
          public MyWindowsService()
          {
              InitializeComponent();
          }
          protected override void OnStart(string[] args)
          {
              host = new ServiceHost(typeof(MyWCFService));
              host.Open();
          }
          protected override void OnStop()
          {
              host.Close();
          }
      }
      
    7. Double click on MyWindowsService, then right-click on the surface and choose Add Installer

    8. Double click on ProjectInstaller.cs and from list of components, choose serviceInstaller1, Then in properties window, set StartType to automatic.

    9. Choose serviceProcessInstaller1 and then in properties window, set Account to LocalSystem.

    10. Add a C# file. (Program.cs)

    11. Modify the content of Program.cs class to:

      static class Program
      {
          static void Main()
          {
              ServiceBase[] ServicesToRun;
              ServicesToRun = new ServiceBase[]
              {
                  new MyWindowsService()
              };
              ServiceBase.Run(ServicesToRun);
          }   
      }
      

    UILayer Project

    1. Create a Windows Forms Application (UILayer)

    2. Add reference to MyServiceLayer project

    3. Open Form1 in design mode, drop a button on it and double click to handle its click event and use the following code:

      private void button1_Click(object sender, EventArgs e)
      {
          ChannelFactory<IMyWCFService> factory = 
              new ChannelFactory<IMyWCFService>("BasicHttpBinding_IMyWCFService");
          IMyWCFService proxy = factory.CreateChannel();
          MessageBox.Show(proxy.Echo("Hello!"));
      }
      
    4. Modify the app.config file to include WCF configurations:

      <?xml version="1.0" encoding="utf-8" ?>
      <configuration>
          <startup> 
              <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
          </startup>
          <system.serviceModel>
              <bindings>
                  <basicHttpBinding>
                      <binding name="BasicHttpBinding_IMyWCFService" />
                  </basicHttpBinding>
              </bindings>
              <client>
                  <endpoint address="http://localhost:8733/Design_Time_Addresses/ServiceLayer/MyWCFService/"
                      binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IMyWCFService"
                      contract="ServiceLayer.IMyWCFService" name="BasicHttpBinding_IMyWCFService" />
              </client>
          </system.serviceModel>
      </configuration>
      
    5. Make sure the endpoint address in app.config of UILayer is same as baseAddress in app.config of ServiceLayer.

    Setup Project

    1. Create a Setup project.
    2. Right-click on project and from Add menu, choose Project output. Then add primary output of the ServiceLayer. (Choose project from dropdown)
    3. Right-click on project and from Add menu, choose Project output. Then add primary output of the UILayer.
    4. Right click on Setup project and choose view Custom Actions.
    5. In custom action windows, for all the nodes (Install, commit, rollback, uninstall), right-click and choose Add custom action and from the application folder, choose primary output of ServiceLayer.
    6. Right click on setup project and choose View FileSystem.
    7. Right click on the root node and choose Add special folder and choose User's startup folder.
    8. Choose Startup folder and then in right pane, right-click and choose create shortcut and from the application folder, choose primary output of UILayer.
    9. Rebuild the solution and setup project.
    10. Install setup by going to out put folder of setup or by right-click on setup project and choosing install.

    After the installation is done, you may want to restart the system to see the effect. The service will be started automatically, and the UILayer will be shown after user logon.

    Click on the button and it will show a MessageBox saying Hello! This content is coming from service.