【问题标题】:how to detect two hot key in win form app like CTRL +C , CTRL+ W如何在win表单应用程序中检测两个热键,如 CTRL + C , CTRL + W
【发布时间】:2014-01-13 12:20:33
【问题描述】:

我的问题是如何检测 win 表单应用程序中的两个热键 CTRL +C,CTRL,K 类似visual studio的评论命令

我需要模拟VS热键来注释一行代码

【问题讨论】:

  • 他在问如何检测序列 - Ctrl+C,然后是 Ctrl+K - 不是一个独立于另一个。
  • @MattDavis 这正是我想要的
  • @mohammedsameeh:如果你想依次处理两个热键,你需要检查 sequence ,检查我的答案。

标签: c# winforms


【解决方案1】:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
   if (e.Modifiers == Keys.Control && e.KeyCode == Keys.C)
   {

   }
}

【讨论】:

    【解决方案2】:

    简单的方法是……有一个Windows API Function叫做ProcessCmdKey,通过重写这个函数我们可以达到我们想要的效果

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
       if (keyData == (Keys.Control | Keys.C)) {
          MessageBox.Show("You have pressed the shortcut Ctrl+C");
          return true;
       }
       return base.ProcessCmdKey(ref msg, keyData);
    }
    

    微软文档可以在here找到

    source

    【讨论】:

    • 当您从另一个question 中提取答案时,请注明出处。
    • 其实我给了原帖的链接。你的喜欢是第二次欺骗
    【解决方案3】:
    private bool _isFirstKeyPressedW = false;
    
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Control & e.KeyCode == Keys.W) 
        {
            _isFirstKeyPressedW = true;
        }
        if (_isFirstKeyPressedW) 
        {
            if (e.Control & e.KeyCode == Keys.S) 
            {
                //write your code 
            } 
            else 
            {
                _isFirstKeyPressedW = e.KeyCode == Keys.W;
            }
        }
    }
    

    【讨论】:

      【解决方案4】:

      如果你想处理 Ctrl + C 后跟 Ctrl+ K 你需要保持一个状态变量。

      将 Form KeyPreview 属性设置为 true 并处理 Form KeyDown 事件。

      试试这个:

         this.KeyPreview=true;
         private bool isFirstKeyPressed= false;
          private void Form1_KeyDown(object sender, KeyEventArgs e)
          {
              if (e.Control && e.KeyCode == Keys.C)
              {               
                  isFirstKeyPressed = true;                
              }
      
      
              if (isFirstKeyPressed)
              {
                  if (e.Control && e.KeyCode == Keys.K)
                  {
                      MessageBox.Show("Ctrl+C and Ctrl+K pressed Sequentially");
                      /*write your code here*/
                      isFirstKeyPressed= false;
                  }
              }
          }
      

      【讨论】:

      • isFirstKeyPressed 在设置为 true 后,应该在 every 情况下重置为 false,对吧?
      • 是的,但如果用户按下Ctrl+CCtrl 并且在按下K 之前,isFirstKeyPressed 本身就会变为 false。
      • @SudhakarTillapudi 您的代码是正确的,但是如果您按 (CTRL+C) 然后再按任意随机字符然后执行 (CTRL+W),则会错过重要的事情,我将发布代码,谢谢
      猜你喜欢
      • 2019-04-29
      • 1970-01-01
      • 2020-03-30
      • 2010-11-20
      • 2011-04-17
      • 2011-02-23
      • 1970-01-01
      • 2011-01-15
      相关资源
      最近更新 更多