0

I am creating a Windows form application in C# using Visual Studio 2008. I have a Button control on my MainForm, which opens AnotherForm on Click event.

What I want to do is:

  1. allow AnotherForm to be opened only once at a time, and
  2. show an error message if the user tries to open another AnotherForm when it is already open, AND bring the already-open AnotherForm to the front.

I was able to limit the AnotherForm open count to 1 by using a static field. However, I am having a hard time achieving requirement #2. It shows an error message, but it does not bring the already-opened AnotherForm to the front.

Here is my code:

**MainForm**
private void BtnToOpenAnotherFornn_Click(object sender, EventArgs e)
{
    AnotherForm af = new AnotherForm();
    if (af.GetNumForms() < 1)
        af.Show();
    else
    {
        MessageBox.Show("AnotherForm is already open.");
        //af.TopMost = true;  //Not working
        //af.BringToFront();   //Not working
    }        
}

**AnotherForm**
private static int NumForms = 0;
public int GetForms(){
    return NumForms;
}

Can someone please tell me how to bring AnotherForm to the front in the else statement?

J.Doe
  • 329
  • 3
  • 14
  • Because a new instance of `AnotherForm` is created on each click of button. You should use `AnotherForm af = new AnotherForm();` at class level. – Ritesh Oct 10 '17 at 17:26
  • 1
    You are trying to make a form topmost and bring to the front that you don't actually want to show. So that just can't work. Simply add a variable of type AnotherForm to your main form class. If it is null then create a new instance of it and subscribe its FormClosed event to set the variable back to null. If it is not null then you know it already exists. Set its WindowState to normal and BringToFront(). – Hans Passant Oct 10 '17 at 17:28
  • Look up the singleton pattern, and refuse nonsense requirements like "show a form on top of everything else while displaying a message box, also on top of everything else". Seriously, do you want the message bx or the form to be visible, and why would you assume creating a new form every time would be a good idea is you only want to have one? – oerkelens Oct 10 '17 at 18:08
  • Thank you! Yeah, I realized a new instance is created on each click.. I tried to declare it at class level, but I noticed that I am unable to. I actually send a variable to the constructor of `AnotherForm` when creating an instance of it. If the variable is locally used, how could this be done? – J.Doe Oct 10 '17 at 18:23
  • To @oerkelens, the message box part can be removed. But still, I want the already-open form to come at the top, so the user can get to it easily. – J.Doe Oct 10 '17 at 18:25

0 Answers0