【问题标题】:Prevent resize from selecting all text in focused ComboBox防止调整大小选择焦点组合框中的所有文本
【发布时间】:2017-03-06 22:31:54
【问题描述】:

我有一个带有 DropDownStyle 的 DropDown 的 ComboBox,只要调整窗口大小,它就会调整大小。如果 ComboBox 中至少有一个 Item 并且它被选中,则调整 ComboBox 的大小会选择所有文本,从而消除用户之前的文本选择。当窗口失去焦点然后重新获得焦点时,也会发生这种情况。有没有人想出一种方法来防止这种情况发生,或者在这种情况发生后恢复文本选择?

This question 描述了未聚焦组合框的相关问题,并包含在 Resize 事件后将 SelectionLength 重置为 0 的解决方案。此事件将是恢复文本选择的一个很好的候选地点,但我不确定如何在文本选择被调整大小之前获取它。

【问题讨论】:

    标签: c# .net winforms combobox


    【解决方案1】:

    但我不确定如何在被调整大小吹走之前获得文本选择

    您可以通过 ResizeBegin 事件的形式收集此信息。

    private int _start;   
    private int _length;
    
    private void Form1_ResizeBegin(object sender, EventArgs e)
    {
        _start = comboBox1.SelectionStart;
        _length = comboBox1.SelectionLength;
    }
    
    private void Form1_ResizeEnd(object sender, EventArgs e)
    {
        comboBox1.SelectionStart = _start;
        comboBox1.SelectionLength = _length;
    }
    

    或在组合框调整大小时不断将其设置回来(也可以通过调整大小事件本身的形式来完成,取决于您的喜好)。使用此选项,用户将看不到任何更改。在上面的示例中,在调整表单大小时将选择整个文本。在下面的它不会。

    private int _start;   
    private int _length;
    
    private void Form1_ResizeBegin(object sender, EventArgs e)
    {
        _start = comboBox1.SelectionStart;
        _length = comboBox1.SelectionLength;
    }
    
    private void comboBox1_Resize(object sender, EventArgs e)
    {
        comboBox1.SelectionStart = _start;
        comboBox1.SelectionLength = _length;
    }
    

    或者,您可以针对不同的事件执行此操作,例如当表单失去焦点时等。

    private int _start;    
    private int _length;
    
    private void Form1_ResizeBegin(object sender, EventArgs e)
    {
        SaveComboBoxSelectionState(comboBox1);
    }
    
    private void comboBox1_Resize(object sender, EventArgs e)
    {
        SetComboBoxSelection(comboBox1, _start, _length);
    }
    
    private void Form1_Deactivate(object sender, EventArgs e)
    {         
        SaveComboBoxSelectionState(comboBox1);
    }
    
    private void Form1_Activated(object sender, EventArgs e)
    {
        SetComboBoxSelection(comboBox1, _start, _length);
    }
    
    private void SaveComboBoxSelectionState(ComboBox comboBox)
    {
        _start = comboBox.SelectionStart;
        _length = comboBox.SelectionLength;
    }
    
    private void SetComboBoxSelection(ComboBox comboBox, int start, int length)
    {
        comboBox.SelectionStart = start;
        comboBox.SelectionLength = length;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-08
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 1970-01-01
      相关资源
      最近更新 更多