确保语句只有在按住某个键时才执行。

如果您按住数字键盘上的5键,它将继续在KeyDown事件处理程序中执行语句。 我怎样才能确保声明只执行一次,即使我按下了键?

感谢您的关注。

private void form_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == Keys.NumPad5) { dados.enviar("f"); //I want this to run only once! } } 

Solutions Collecting From Web of "确保语句只有在按住某个键时才执行。"

你可以在键上设置标志,并在键上复位。

  private bool isPressed = false; public Form1() { InitializeComponent(); } private void Form1_KeyDown(object sender, KeyEventArgs e) { if(e.KeyCode == Keys.B && !isPressed ) { isPressed = true; // do work } } private void Form1_KeyUp(object sender, KeyEventArgs e) { if (isPressed ) isPressed = false; } 
 bool alreadyPressed = false; ... if (e.KeyCode == Keys.NumPad5 && ! alreadyPressed) { alreadyPressed = true; ...