{
switch (keyData)
{
case Keys.Right:
MessageBox.Show("Right");
break;
case Keys.Left:
MessageBox.Show("Left");
break;
case Keys.Up:
MessageBox.Show("up");
break;
case Keys.Down:
MessageBox.Show("down");
break;
case Keys.Space:
MessageBox.Show("space");
break;
case Keys.Enter:
MessageBox.Show("enter");
break;
}
//return false;//如果要调用KeyDown,这里一定要返回false才行,否则只响应重写方法里的按键.
//这里调用一下父类方向,相当于调用普通的KeyDown事件.//所以按空格会弹出两个对话框
//return base.ProcessCmdKey(ref msg, keyData);
return true;//这里return true 否则控件焦点会跟着方向键改变
}
第一种:重载ProcessCmdKey方法,直接在winform程序中加入这个就可以了
protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
{
if (keyData == (Keys.Control | Keys.N))
{
MessageBox.Show("按下了Control+N")
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
第二中方法:
在form的keydown事件中捕捉按钮事件,程序如下,
需要注意:form的KeyPreview 属性设置为true,否则捕捉不到事件
#region 快捷键
private void PhoneForm_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.S)
{
Control[] controls = this.pCallList.Controls.Find("recorder",true);
if (controls.Length > 0)
{
((CallRecorder)controls[0]).btnSave_Click(null, null);
}
}
else if (e.Control && e.KeyCode == Keys.P)
{
Control[] controls = this.pCallList.Controls.Find("recorder", true);
if (controls.Length > 0)
{
((CallRecorder)controls[0]).btnSend_Click(null, null);
}
}
else if (e.Control && e.KeyCode == Keys.T)
{
foreach (Control call in panelCalls.Controls)
{
if (call is UserCall)
{
if (((UserCall)call).isTalking)
{
((UserCall)call).btnHangupCall_Click(null, null);
}
else
{
((UserCall)call).btnAcceptCall_Click(null, null);
}
}
}
}
}
#endregion