Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: showing an invisible form

Tags:

c#

forms

I have the following code in C#:

Form f = new MyForm();
f.Visible = false;
f.Show();
f.Close();

Despite the f.Visible = false, I am seeing a flash of the form appearing and then disappearing. What do I need to do to make this form invisible?

I need to show the form (invisibly) during the splash of my app because doing this removes a cold start delay when showing this form.

like image 819
Craig Johnston Avatar asked Mar 02 '11 13:03

Craig Johnston


2 Answers

If you want to show the form without actually seeing it, you can do this:

  public Form1()
  {
     InitializeComponent();
     this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
     this.ShowInTaskbar = false;
     this.Load += new EventHandler(Form1_Load);
  }

  void Form1_Load(object sender, EventArgs e)
  {
     this.Size = new Size(0, 0);
  }

If at a later point you want to show it, you can just change everything back. Here is an example after 10 seconds, it shows the form:

  Timer tmr = new Timer();
  public Form1()
  {
     tmr.Interval = 10000;
     tmr.Tick += new EventHandler(tmr_Tick);
     tmr.Start();

     InitializeComponent();
     this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
     this.ShowInTaskbar = false;
     this.Load += new EventHandler(Form1_Load);
  }

  void tmr_Tick(object sender, EventArgs e)
  {
     this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
     this.ShowInTaskbar = true;
     this.Size = new Size(300, 300);
  }

  void Form1_Load(object sender, EventArgs e)
  {
     this.Size = new Size(0, 0);
  }
like image 147
SwDevMan81 Avatar answered Oct 10 '22 16:10

SwDevMan81


By far the simplest way to keep a form invisible is just by not showing it. It is a big deal in Winforms, calling Show() or setting the Visible property to true (same thing) does a lot of things. It is the way the native Windows window gets created. In typical .NET 'lazy' fashion. Any attempt to set Visible back to false (like in OnLoad) will be defeated.

Technically it is possible, you have to override the SetVisibleCore() method. Like this:

    protected override void SetVisibleCore(bool value) {
        if (!this.IsHandleCreated) {
            this.CreateHandle();
            value = false;   // Prevent window from becoming visible
        }
        base.SetVisibleCore(value);
    }

This ensures that the window doesn't become visible the first time you call Show(). Which is handy when you have NotifyIcon for example, you typically want the icon directly in the notification area and only display a window when the user clicks on the icon. Beware that OnLoad() doesn't run until the window actually becomes visible so move code to the constructor or the override if necessary.

like image 22
Hans Passant Avatar answered Oct 10 '22 17:10

Hans Passant