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
Yikes! By setting F2 to null in your else clauses, you are going to end up with multiple Form2 windows since you are basically orphaning the current instance.
Ahh, Ill comment out the =null of the subroutines.. With help of folk like you, I will slowly learn!

I wasnt sure if I needed to return the form to NULL state or not, so I did it... VS didnt moan at me so the code compiles but "its not good".

Thank you!
 
Last edited by a moderator:
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!
 

Latest posts

Back
Top Bottom