Resolved this. works, but form1. does not, confused..

Program4Food

Active member
Joined
Nov 22, 2021
Messages
40
Programming Experience
10+
See the code below, I can call this. to minimize the form (form1, the only form in the project), but if I try to call it directly (like I used to be able to do in old VB) by calling it form1., I get an error. I do not understand why I cant call the form directly...

Screen shot showing VS2012 error is attached.

I am self taught so my knowledge and understanding is growing, but is limited. :-( Thank you for your time.

calling a form directly by name does not work:
        private void Form1_Load(object sender, EventArgs e)
        {

           //  this.WindowState = System.Windows.Forms.FormWindowState.Minimized;

             Form1.WindowState = System.Windows.Forms.FormWindowState.Minimized;

        }
 

Attachments

  • callingaformdirectlygiveserrors.jpg
    callingaformdirectlygiveserrors.jpg
    48.7 KB · Views: 14
Try:
Without using Lazy:
Form2 _form2;

Form2 EnsureForm2()
{
    if (_form2 == null)
        _form2 = new Form2();
    return _form2;
}

void btnShow_Click(object sender, EventArgs e)
    => EnsureForm2().Show();

void btnHide_Click(object sender, EventArgs e)
    => EnsureForm2().Hide();

void btnMinimize_Click(object sender, EventArgs e)
    => EnsureForm2().WindowState = FormWindowState.Minimized;

void btnRestore_Click(object sender, EventArgs e)
{
    EnsureForm2().WindowState = FormWindowState.Normal;
    EnsureForm2().Show();
}

Using Lazy:
Lazy<Form2> _form2;
Form2 MyForm2 => _form2.Value;

Form1()
{
    InitializeComponent();
  
    _form2 = new Lazy<Form2>(() => new Form2());
}

void btnShow_Click(object sender, EventArgs e)
    => MyForm2.Show();

void btnHide_Click(object sender, EventArgs e)
    => MyForm2.Hide();

void btnMinimize_Click(object sender, EventArgs e)
    => MyForm2.WindowState = FormWindowState.Minimized;

void btnRestore_Click(object sender, EventArgs e)
{
    MyForm2.WindowState = FormWindowState.Normal;
    MyForm2.Show();
}
 
Ahh... much more efficient, and cleaner. THANK YOU!!

I am doing 3 new things at once, so I value your help! I am learning a new Visual Studio, dotNet and C#.

I have many years of VB 6.0 under the hood, a lot of updates and changes = A lot of new things to learn!
 
This:
C#:
if (_form2 == null)
should be this:
C#:
if (_form2 == null || _form2.IsDisposed)
When you close a form that was displayed by calling Show, that form object is disposed and cannot be shown again, thus a new instance would need to be created.

Also, I would generally use a read-only property rather than a method. That feels a bit more natural to me, but it amounts to the same thing.
 
Back
Top Bottom