Search code examples
.netwinformshidestartupdelphi-prism

How to hide the mainform and still run the program?


I want to run my program with the icon showing in the system tray but without the mainform showing from the start.

Edit:

  lMainForm := new MainForm; 
  lMainForm.ShowInTaskbar := true;
  Application.Run(lMainForm);

Didn't work. As soon as Application.Run is executed, mainform is displayed along with the icon in the system tray.


Solution

  • The problem you have at the moment is that you are calling the Application.Run overload that takes the main form as a parameter. This will show the main form which you do not want.

    Instead you should call one of the other Application.Run overloads.

    For example you can call the no parameter overload of Application.Run. Make sure that you have created and installed your notify icon before you do so. And also create, but do not show your main form.

    When you are ready to show your main form, in response to an action on the notify icon, call lMainForm.Show. You will also wish to arrange that clicking the close button on the form merely hides the form rather than closing it. I'm assuming that you want your main form instance to persist hidden in the background.

    So the top-level of your program would look like this:

    //create and show the notify icon here
    lMainForm := new MainForm; 
    lMainForm.ShowInTaskbar := true;
    lMainForm.Visible := false;//I believe this is the default in any case
    Application.Run;
    

    You'll need to add an item to the notify icon menu that closes the application. Implement this with:

    Application.Exit;
    

    If you need more fine grained control over the application lifetime then you may be better off using the Application.Run overload that receives an ApplicationContext.

    Since I don't have Prism at hand I have checked this out with C#/WinForms and I hope it transfers alright to Prism!