How to hide the mainform and still run the program?

2.2k views Asked by At

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.

3

There are 3 answers

0
David Heffernan On BEST ANSWER

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!

2
CodingWithSpike On

Have you tried:

lMainForm.WindowState := System.Windows.Forms.FormWindowState.Minimized;

or

lMainForm.Hide(); // call on application start
0
Hans Passant On

You do it by overriding the SetVisibleCore() method. Like this:

    protected override void SetVisibleCore(bool value) {
        if (!this.IsHandleCreated) {
            CreateHandle();
            value = false;
        }
        base.SetVisibleCore(value);
    }

Beware that the Load event won't fire. Be sure to move any code you have there to either the constructor (preferred) or this override.

This code suppresses the window only once. You can call Show() or setting Visible = true later to make the window show up as normal. You'd typically do so in the Click event handler of a context menu item for the NotifyIcon.