Click here to Skip to main content
14,384,739 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hi,

I'm trying to make one button have two functions for my C# project, press it once to open a form and then press it again to close that same for that opened, how can I do this please? I can show you the code I had done so far, it's nothing special.

The button opens my setting form that has setting such as turn music on and off, and other functions for the user.

What I have tried:

//Code below opens the game settings menu.
private void SettingsBTN_Click(object sender, EventArgs e)
{
Kid_Merchant_Hero.GameSettings f = new Kid_Merchant_Hero.GameSettings();
f.Show();
}
Posted
Updated 20-Apr-19 5:37am
Rate this:
Please Sign up or sign in to vote.

Solution 2

The first problem is that you are storing the new form instance in a local variable, which will be discarded when you exit the handler method.
Start by moving it to class level:
private Kid_Merchant_Hero.GameSettings gameSettings = null;
Then you can use that to decide what to do:
private void SettingsBTN_Click(object sender, EventArgs e)
{
if (gameSettings == null)
   {
   gameSettings = new Kid_Merchant_Hero.GameSettings();
   gameSettings.FormClosed += gameSettings.FormClosed;
   gameSettings.Show();
   SettingsBTN.Text = "Close";
   }
else
   {
   gameSettings.Close();
   }
}
Handle the FormClosed event to clear the form:
private void gameSettings_FormClosed(object sender, FormClosedEventArgs e)
    {
    gameSettings = null;
    SettingsBTN.Text = "Open";
    }
And you're done.
   
v2
Comments
Member 14176556 20-Apr-19 11:02am
   
This worked perfectly, thanks :D and super happy with the quickness of your reply, thanks.
OriginalGriff 20-Apr-19 11:08am
   
You're welcome!
Rate this:
Please Sign up or sign in to vote.

Solution 3

You can enumerate all the Windows / forms you've created (WPF and Windows.Form apps). You can then decide to show, hide, discard any of them; or create extras without maintain a separate collection.

How to: Get all Windows in an Application | Microsoft Docs[^]
   
Comments
Member 14176556 20-Apr-19 11:02am
   
thanks for your solution.
Rate this:
Please Sign up or sign in to vote.

Solution 1

I am not sure, what data your GameSettings object holds, you need to provide more details, but is there a flag that can represents if your form is open, if yes then do something like below:

if(!f.IsOpen)
f.Show();
else
f.Close();

else, you can create 2 event handlers, one having open and other having close form logic, and in each of these, detach current event and and attach other event on button click.
Provide more details, if none of these work for you
   
Comments
Member 14176556 20-Apr-19 11:02am
   
thanks for your solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100