How to hide the mainform and still run the program?

心不动则不痛 提交于 2020-01-02 08:09:55

问题


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.


回答1:


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:


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.




回答3:


Have you tried:

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

or

lMainForm.Hide(); // call on application start


来源:https://stackoverflow.com/questions/8764745/how-to-hide-the-mainform-and-still-run-the-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!