【问题标题】:Stop the Bell on CTRL-A (WinForms)在 CTRL-A 上停止响铃(WinForms)
【发布时间】:2008-10-22 13:26:44
【问题描述】:

CTRL-A 用于在 Winforms 应用程序中选择文本时,如何阻止系统铃声响起?

这就是问题所在。创建一个 Winforms 项目。在窗体上放置一个文本框并在窗体上添加以下事件处理程序以允许 CTRL-A 选择文本框中的所有文本(无论哪个控件具有焦点)。

void Form1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.A && e.Modifiers == Keys.Control)
    {
        System.Diagnostics.Debug.WriteLine("Control and A were pressed.");
        txtContent.SelectionStart = 0;
        txtContent.SelectionLength = txtContent.Text.Length;
        txtContent.Focus();
        e.Handled = true;
    }
}

它可以工作,但是尽管 e.Handled = true,每次按下 CTRL-A 时系统铃声都会响起。


感谢您的回复。

Form 上的 KeyPreview 设置为 true - 但这并不能阻止系统铃声响起 - 这是我要解决的问题 - 烦人。

【问题讨论】:

    标签: winforms keyeventargs


    【解决方案1】:
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.A)
            {
                this.textBox1.SelectAll();
                e.SuppressKeyPress = true;
            }
        }
    

    希望对你有帮助

    【讨论】:

      【解决方案2】:

      感谢 MSDN 论坛的帖子 - 只有当文本框处于多行模式并且您想实现 Ctrl+A 以全选时,才会出现此问题。 p>

      解决办法

      protected override bool ProcessCmdKey(ref Message msg, Keys keyData) 
      {
        if (keyData == (Keys.A | Keys.Control)) {
          txtContent.SelectionStart = 0;
          txtContent.SelectionLength = txtContent.Text.Length;
          txtContent.Focus();
          return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
      }
      

      【讨论】:

        【解决方案3】:

        这对我有用:

        将表单上的 KeyPreview 设置为 True。

        希望对您有所帮助。

        【讨论】:

          【解决方案4】:

          @H7O 解决方案不错,但我对其进行了一些改进,以便在表单上增加 TextBox 组件。

          private void textBox_KeyDown(object sender, KeyEventArgs e)
          {
            if (e.Control && e.KeyCode == Keys.A)
            {
              ((TextBox)sender).SelectAll();
              e.SuppressKeyPress = true;
            }
          }
          

          【讨论】:

            猜你喜欢
            • 2012-11-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-03-16
            相关资源
            最近更新 更多