简体   繁体   中英

C #Prevent from creating additional form

I have a form Form1 with a button that creates additional forms. However, I would like to only create 1 additional form at a time. The following is my code implementation for the following. I tried to use Focus property but it doesn't work.

private void addLocation(object sender, MouseClickEventArgs e)
{
   Form2 form2 = new Form2();
   form2.Show();
   form2.Focus();
}

Use the Application.OpenForms collection to check if you have already an instance of that form open.

private void addLocation(object sender, MouseClickEventArgs e)
{
   Form2 form2 = Application.OpenForms.OfType<Form2>().SingleOrDefault();
   if(form2 == null)
   {
       form2 = new Form2();
       form2.Show();
       form2.Focus();
   }
}

So if the form opened it should be brought to front and focused ( Show emulation ), if not opened then created and showed :

  // If there're many instances, let's take the last one
  Form2 form = Application.OpenForms
    .OfType<Form2>()
    .LastOrDefault(); 

  if (null == form) {
    form = new From2();
    form.Show();
  }
  else {
    // Show emulation: 
    //   - we don't want minimized window, 
    //   - window should be at front
    //   - window should have a keyboard focus

    if (form.WindowState == FormWindowState.Minimized)
      form.WindowState = FormWindowState.Normal;

    form.BringToFront();

    if (form.CanFocus)
      form.Focus(); 
  } 

You can disable the user from clicking on the button by changing the cursor then restore that after the code create the form is done or in the form it self

// Set cursor as hourglass

Cursor.Current = Cursors.WaitCursor;

// Execute your time-intensive hashing code here...

// Set cursor as default arrow Cursor.Current = Cursors.Default;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM