c#如何从文本框中捕获Ctrl-R

问题描述 投票:0回答:2

我有一个文本框,我正在尝试确定是否在此文本框中按下了Ctrl-R。我可以使用以下方法分别检测密钥:

private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    if(e.KeyChar == (char)Keys.R)
    {
        // ...
    }
    if ((Control.ModifierKeys & Keys.Control) == Keys.Control)
    {
        // ...
    }
}

如何确定它们是否同时按下?

c# keystroke
2个回答
5
投票

如果可能,将您的活动更改为KeyDown / KeyUp,一切都会更容易。 (请注意,此解决方案并不总是适用)

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
   if (e.KeyData == (Keys.Control | Keys.R))
   {

   }
}

3
投票

请参阅Mitch关于如何正确构造位标志逻辑的答案,只要他取消删除即可。如果他没有决定,这将是有用的。你基本上需要检查两个条件是否同时为真:

bool isRKeyPressed = e.KeyChar == (char)Keys.R;
bool isControlKeyPressed = (Control.ModifierKeys & Keys.Control) == Keys.Control;

if (isRKeyPressed && isControlKeyPressed)
{
    // Both ...
}
else if (isRKeyPressed)
{
    // R key only ...
}
else if (isControlKeyPressed)
{
    // CTRL key only ...
}
else
{
    // None of these...
}

扔掉你不关心的任何这些检查。

此外,您可能想要查看这种替代方法:http://www.codeguru.com/columns/experts/article.php/c4639

他们在形式上覆盖ProcessCmdKey方法(可能在个别控件上?):http://msdn.microsoft.com/en-us/library/system.windows.forms.control.processcmdkey.aspx

© www.soinside.com 2019 - 2024. All rights reserved.