Minimize and Hide Winform on Form Load

2019-08-14 03:18发布

问题:

I have a Windows Form in a C# program with the FormBorderStyle set to FixedToolWindow.

The window doesn't have the normal control box, but the user can still minimize it from a menu. There is also a setting for the window to start in a minimized state.

When the user clicks the minimize button it called the following function:

private void minimizeWindow()
{
    timer1.Enabled = false;            
    this.WindowState = FormWindowState.Minimized;
    this.Hide();
}

The window becomes a small box in the bottom left of the screen, then disappears (from the this.hide call). When the same function is called from within the Form_Load method (when the setting is to start minimized) it minimizes but does not disappear.

My guess is that because I am hiding the form before reaching the end of Form_Load it is being shown again when it reaches the end of the method. Is there any way to ensure the form hides when it is loaded (it is maximised again from a system tray icon)?

Edit: Included all code from form load

private void Form1_Load(object sender, EventArgs e)
{
    this.Left = windowXPos;
    this.Top = windowYPos;
    sysTrayIcon.MouseDoubleClick += new MouseEventHandler(sysTrayIcon_MouseDoubleClick);
    sysTrayIcon.BalloonTipText = "Timers Running";
    this.sysTrayIcon.Icon = this.Icon;
    sysTrayIcon.Visible = true;
    sysTrayIcon.ShowBalloonTip(500);
    Start();  //sets up timers
    if (startMinimized)
    {
        minimizeWindow();
    }
}

回答1:

It might be best to change your logic slightly, and instead of showing the form at all, create an instance of it (var foo = new MyForm()) but don't call .Show() so it will never be shown until triggered from your system tray icon.