如果按下某个键,我试图更改一个布尔值,但是当释放时会恢复为false,所以我只能触发if语句,如果所有参数都正确并且按下了一个键。
public class boolean
{
public static Boolean keyPresed = false;
}
private void mainForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.A)
{
MessageBox.Show(" just for debugging ");
boolean.keyPresed = true;
}
else {
boolean.keyPressed = false;
}
if (tileBuyPlayer2.Checked && ownerShipsPlayer2.peacockOwner == false && boolean.keyPresed == true)
{
// do this sorry not on here cause how big it is
}
}
}
答案 0 :(得分:0)
您可以将 keyAPressed 声明为global var in this class
,并在KeyDown事件中声明reset
:
public class DemoClass
{
public static Boolean keyAPressed = false;
private void mainForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
MessageBox.Show(" just for debugging ");
keyAPressed = true;
}
else
{
keyAPressed = false;
}
if (keyAPressed == true)
{
// Reset keyAPressed to false
keyAPressed = false
if (tileBuyPlayer2.Checked && ownerShipsPlayer2.peacockOwner == false)
{
// do this sorry not on here cause how big it is
}
}
}
}
或使用 KeyUp 事件到reset keyAPressed
:
public class DemoClass
{
public static Boolean keyAPressed = false;
private void mainForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
MessageBox.Show(" just for debugging ");
keyAPressed = true;
}
else
{
keyAPressed = false;
}
if (tileBuyPlayer2.Checked && ownerShipsPlayer2.peacockOwner == false && keyAPressed == true)
{
// do this sorry not on here cause how big it is
}
}
private void mainForm_KeyUp(object sender, KeyEventArgs e)
{
keyAPressed = false;
}
}
答案 1 :(得分:0)
如果您乐意尝试微软的反应式框架,那么您可以尝试这样做:
var keyDown = Observable.FromEventPattern<KeyEventArgs>(mainForm, "KeyDown");
var query =
from kd in keyDown
where kd.EventArgs.KeyCode == Keys.A
where tileBuyPlayer2.Checked
where ownerShipsPlayer2.peacockOwner == false
select kd;
query.Subscribe(x =>
{
// do your code here
});
我可能错过了你想要做的事情,但我认为这会让事情变得更容易。