当 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 时系统铃声都会响起。
感谢您的回复。
表单上的KeyPreview设置为true - 但这并不能阻止系统响铃发声 - 这是我试图解决的问题 - 烦人。
答案 0 :(得分:21)
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
{
this.textBox1.SelectAll();
e.SuppressKeyPress = true;
}
}
希望这会有所帮助
答案 1 :(得分:6)
感谢MSDN论坛帖子 - 只有当文本框处于多行模式并且你想实现 Ctrl + A 才能选择全部时,才会出现此问题。
这是解决方案
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);
}
答案 2 :(得分:1)
这对我有用:
将表单上的KeyPreview设置为True。
希望有所帮助。
答案 3 :(得分:1)
@ H7O解决方案很好,但是我对表单上的多个TextBox组件进行了一些改进。
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.A)
{
((TextBox)sender).SelectAll();
e.SuppressKeyPress = true;
}
}