sooprise sooprise - 3 months ago 27
C# Question

Making a form be invisible when it first loads

Currently, the form's opacity is 0%, so that when it loads, it should be invisible, but when the form loads, it's visible for a few seconds. Since the default opacity is set to 0% and the form's visibility is set to false before it's opacity is set back to 100%, I would think that the form should be invisible until I tell it to.

public FormMain()
{
InitializeComponent();
this.Visible = false;
this.Opacity = 1.00;
}


How can I make my form invisible as a default?

Answer

It's possible. You have to prevent the Application class from making the form visible. You cannot tinker with Application, that's locked up. But this works:

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

This is a one-time cancellation, your next call to Show() or setting Visible = true will make it visible. You'd need some kind of trigger, a NotifyIcon context menu is typical. Beware that the Load event won't run until it actually gets visible. Everything else works like normal, calling the Close() method terminates the program.