【问题标题】:.NET BUG? SplitContainer Split move selects all text of contained controls.NET 错误? SplitContainer 拆分移动选择包含的控件的所有文本
【发布时间】:2010-11-26 18:10:01
【问题描述】:

我有一些嵌套的 SplitContainers,并且发生了一种不良行为。每次拆分器移动时,控件都会选择其文本(文本被突出显示),特别是组合框。

我不知道为什么会发生这种情况。这个问题很容易重现。你只需要:

  1. 创建表单。
  2. A 将一个拆分容器放入其中。
  3. 添加一个包含一些项目的组合框。
  4. 锚定组合框的左侧和右侧。
  5. 编译
  6. 移动分离器

您将看到 ComboBox 的文本将突出显示。

如何防止这种情况发生?或者至少,从 ComboBoxes 中删除突出显示?

非常感谢您的帮助!

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    这是 Windows 原生组合框控件中的一个古老错误。是的,它在收到 WM_SIZE 消息时选择文本。这是 DropDownStyle = DropDown 特有的。

    这是一种可能的解决方法:

    using System;
    using System.Windows.Forms;
    
    class MyComboBox : ComboBox {
        protected override void OnResize(EventArgs e) {
            if (!this.Focused && this.DropDownStyle == ComboBoxStyle.DropDown) {
                this.SelectionLength = 0;
            }
            base.OnResize(e);
        }
    }
    

    【讨论】:

    • 正是我所需要的,谢谢!我会发布VB版本,以防像我这样的人接手VB项目并且没有出路,lol。
    【解决方案2】:

    @hansPassant 答案的 VB 版本,我今天需要它。对于接手 VB 项目但没有出路的人来说,这可能会有所帮助:

    修改特定控件的 Resize 事件(此处为ComboBox1):

    Private Sub ComboBox1_Resize(sender As Object, e As EventArgs) Handles ComboBox1.Resize
        Dim curr_combo = TryCast(sender, System.Windows.Forms.ComboBox)
    
        If ((Not curr_combo.Focused) And curr_combo.DropDownStyle = ComboBoxStyle.DropDown) Then
            curr_combo.SelectionLength = 0
        End If
    End Sub
    

    要创建通用事件,您可以附加到多个ComboBoxs:

    Private Sub ComboBox_Resize(sender As Object, e As EventArgs)
        Dim curr_combo = TryCast(sender, System.Windows.Forms.ComboBox)
    
        If ((Not curr_combo.Focused) And curr_combo.DropDownStyle = ComboBoxStyle.DropDown) Then
            curr_combo.SelectionLength = 0
        End If
    End Sub
    

    然后将其添加到您的 ComboBox 控件之一,如下所示:

    AddHandler my_combo.Resize, AddressOf ComboBox_Resize
    

    或者像这样对他们所有人:

    For Each obj As Object In Me.Controls()
        Dim combo = TryCast(obj, ComboBox)
        If TypeOf combo Is ComboBox Then
            AddHandler combo.Resize, AddressOf ComboBox_Resize
        End If
    Next
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      • 2015-07-10
      相关资源
      最近更新 更多