Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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 4:37am

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[^]
 
Share this answer
 
Comments
Member 14176556 20-Apr-19 11:02am    
thanks for your solution.
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:
C#
private Kid_Merchant_Hero.GameSettings gameSettings = null;
Then you can use that to decide what to do:
C#
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:
C#
private void gameSettings_FormClosed(object sender, FormClosedEventArgs e)
    {
    gameSettings = null;
    SettingsBTN.Text = "Open";
    }
And you're done.
 
Share this answer
 
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!
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
 
Share this answer
 
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, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900