[英]How can I both show and hide a form with same key?
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. 我正在用表格制作RPG游戏,但我想不出如何仅用一个键来显示和隐藏特定表格。 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.
例如,当我按下“ C”键时,我希望它通过PlayerInfo面板向我显示该表单,而当我再次按下“ C”键时,我希望它隐藏它。
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 您需要一个if / else语句,现在同时调用了两个if语句,因此最终您会在按下键时显示并隐藏在同一调用中
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.
如果您在回调中对其进行初始化,则始终将其设置为false。
I would add a method and a property in PlayerInfo class, called toggle
我会在PlayerInfo类中添加一个方法和一个属性,称为
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.使用你的代码,你总是会得到它的知名度真,直到你让
visible
的全局变量。 ProbablyplayerInfo
too be global, else it will be a new instance every time.也许
playerInfo
也是全局的,否则每次都会是一个新实例。
Global declaration: 全局声明:
bool visible = false;
PlayerInfo playerInfo = new PlayerInfo(this);
KeyPress
Method signature: KeyPress
方法签名:
private void KeyPress(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.C)
{
if (!visible)
{
playerInfo.Show();
visible = true;
}
else
{
playerInfo.Hide();
visible = false;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.