I am making an RPG game with forms and I can't figure out how to show and hide a particular form with only one key. For example when I press the "C" key I want it to show me the form with the PlayerInfo panel, and when I press "C" again I want it to hide it.
private void KeyPress(object sender, KeyEventArgs e)
{
PlayerInfo playerInfo = new PlayerInfo(this);
bool visible = false;
if (e.KeyCode == Keys.C)
{
if (visible == false)
{
playerInfo.Show();
visible = true;
}
}
if (e.KeyCode == Keys.C)
{
if (visible)
{
playerInfo.Hide();
visible = false;
}
}
}
You need an if/else statement, right now both if's are getting called so you end up showing and then hiding it in the same call when you hit the key
bool visible = false;
private void KeyPress(object sender, KeyEventArgs e)
{
PlayerInfo playerInfo = new PlayerInfo(this);
if (e.KeyCode == Keys.C)
{
if (visible == false)
{
playerInfo.Show();
visible = true;
}
else if (visible)
{
playerInfo.Hide();
visible = false;
}
}
}
EDIT: Sorry, I didn't notice that your visible variable was a local variable. You need to make this a class variable, and set it on construction of your object. If you initialize it in your callback you'll always be setting it to false.
I would add a method and a property in PlayerInfo class, called toggle
public class PlayerInfo {
// your stuff
public bool IsVisible {get;set;}
public void Toggle() {
if (IsVisible)
Hide()
else
Show()
IsVisible = !IsVisible
}
}
Using your code you will always get it's visibility true until u make
visible
as global variable. ProbablyplayerInfo
too be global, else it will be a new instance every time.
Global declaration:
bool visible = false;
PlayerInfo playerInfo = new PlayerInfo(this);
KeyPress
Method signature:
private void KeyPress(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.C)
{
if (!visible)
{
playerInfo.Show();
visible = true;
}
else
{
playerInfo.Hide();
visible = false;
}
}
}
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.