如果我SelectAll从GotFocus事件处理程序中调用,它不适用于鼠标 - 一旦释放鼠标,选择就会消失。
SelectAll
GotFocus
编辑:人们喜欢 Donnelle 的回答,我将尝试解释为什么我不像接受的答案那样喜欢它。
不知道为什么它在GotFocus事件中失去了选择。
但一种解决方案是对事件进行GotKeyboardFocus选择GotMouseCapture。这样它就会一直工作。
GotKeyboardFocus
GotMouseCapture
- 编辑 -
在此处添加一个示例,向人们展示如何解决上述一些缺点:
private void TextBox_GotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { // Fixes issue when clicking cut/copy/paste in context menu if (textBox.SelectionLength == 0) textBox.SelectAll(); } private void TextBox_LostMouseCapture(object sender, MouseEventArgs e) { // If user highlights some text, don't override it if (textBox.SelectionLength == 0) textBox.SelectAll(); // further clicks will not select all textBox.LostMouseCapture -= TextBox_LostMouseCapture; } private void TextBox_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { // once we've left the TextBox, return the select all behavior textBox.LostMouseCapture += TextBox_LostMouseCapture; }