Programing

양식이 표시 될 때 TextBox의 텍스트가 강조 표시 (선택)되는 이유는 무엇입니까?

lottogame 2020. 10. 16. 07:00
반응형

양식이 표시 될 때 TextBox의 텍스트가 강조 표시 (선택)되는 이유는 무엇입니까?


TextBox다음과 같이 문자열로 설정 한 C #에서를 포함하는 양식이 있습니다.

textBox.Text = str;

양식이 표시 될 때 texbox의 텍스트가 강조 표시 / 선택된 것처럼 보이는 이유는 무엇입니까?


텍스트 상자는 TabIndex0이고 TabStoptrue로 설정됩니다. 이것은 폼이 표시 될 때 컨트롤에 포커스가 주어짐을 의미합니다.

다른 컨트롤에 0 TabIndex(있는 경우)을 지정하고 텍스트 상자에 다른 탭 인덱스 (> 0)를 지정하거나 TabStop텍스트 상자에 대해 false로 설정 하여이 문제가 발생하지 않도록 할 수 있습니다.


Windows Forms에서 TextBox의 기본 동작은 처음으로 탭하여 포커스를 받으면 모든 텍스트를 강조 표시하지만 클릭 한 경우에는 강조 표시하지 않습니다. Reflector에서 TextBoxOnGotFocus()오버라이드를 보면 이것을 볼 수 있습니다.

protected override void OnGotFocus(EventArgs e)
{
    base.OnGotFocus(e);
    if (!this.selectionSet)
    {
        this.selectionSet = true;
        if ((this.SelectionLength == 0) && (Control.MouseButtons == MouseButtons.None))
        {
            base.SelectAll();
        }
    }
}

우리가 좋아하지 않는 행동을 일으키는 if 문입니다. 또한 부상에 대한 모욕을 추가하기 위해 Text속성의 세터 selectionSet는 텍스트가 다시 할당 될 때마다 해당 변수를 맹목적으로 재설정합니다 .

public override string Text
{
    get
    {
        return base.Text;
    }
    set
    {
        base.Text = value;
        this.selectionSet = false;
    }
}

따라서 TextBox가 있고 그 안에 탭이 있으면 모든 텍스트가 선택됩니다. 클릭하면 강조 표시가 제거되고 다시 탭하면 캐럿 위치 (및 선택 길이 0)가 유지됩니다. 그러나 프로그래밍 방식으로 new를 설정 Text하고 TextBox에 다시 탭하면 모든 텍스트가 다시 선택됩니다.

당신이 나와 같고이 행동이 성 가시고 일관성이 없다고 생각한다면,이 문제를 해결하는 두 가지 방법이 있습니다.

첫 번째이자 아마도 가장 쉬운 방법은 양식 selectionSet을 호출 하고 변경 될 때마다 설정을 트리거하는 것입니다 .DeselectAll()Load()Text

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);

    this.textBox2.SelectionStart = this.textBox2.Text.Length;
    this.textBox2.DeselectAll();
}

( DeselectAll()그냥 SelectionLength0으로 설정 합니다. 실제로 변수 SelectionStart를 뒤집습니다 . 위의 경우 시작을 텍스트의 끝으로 설정하므로 to 호출 이 필요하지 않습니다.하지만 다른 위치로 설정하면 다음과 같습니다. 텍스트의 시작 부분을 호출 한 다음 호출하는 것이 좋습니다.)TextBoxselectionSetDeselectAll()

보다 영구적 인 방법은 상속을 통해 원하는 동작으로 자체 TextBox를 만드는 것입니다.

public class NonSelectingTextBox : TextBox
{
    // Base class has a selectionSet property, but its private.
    // We need to shadow with our own variable. If true, this means
    // "don't mess with the selection, the user did it."
    private bool selectionSet;

    protected override void OnGotFocus(EventArgs e)
    {
        bool needToDeselect = false;

        // We don't want to avoid calling the base implementation
        // completely. We mirror the logic that we are trying to avoid;
        // if the base implementation will select all of the text, we
        // set a boolean.
        if (!this.selectionSet)
        {
            this.selectionSet = true;

            if ((this.SelectionLength == 0) && 
                (Control.MouseButtons == MouseButtons.None))
            {
                needToDeselect = true;
            }
        }

        // Call the base implementation
        base.OnGotFocus(e);

        // Did we notice that the text was selected automatically? Let's
        // de-select it and put the caret at the end.
        if (needToDeselect)
        {
            this.SelectionStart = this.Text.Length;
            this.DeselectAll();
        }
    }

    public override string Text
    {
        get
        {
            return base.Text;
        }
        set
        {
            base.Text = value;

            // Update our copy of the variable since the
            // base implementation will have flipped its back.
            this.selectionSet = false;
        }
    }
}

You maybe tempted to just not call base.OnGotFocus(), but then we would lose useful functionality in the base Control class. And you might be tempted to not mess with the selectionSet nonsense at all and simply deselect the text every time in OnGotFocus(), but then we would lose the user's highlight if they tabbed out of the field and back.

Ugly? You betcha. But it is what it is.


The answers to this question helped me a lot with a similar problem but the simple answer is only hinted at with a lot of other complex suggestions. Just set SelectionStart to 0 after setting your Text. Problem solved!

Example:

yourtextbox.Text = "asdf";
yourtextbox.SelectionStart = 0;

You can also choose the tab order for your form's controls by opening:

View->Tab Order

Note that this option is only available in "View" if you have the Form design view open.

Selecting "Tab Order" opens a view of the Form which allows you to choose the desired tab order by clicking on the controls.


To unhighlight a text field, with VS 2013, try init with:

myTextBox.GotFocus += new System.EventHandler(this.myTextBox_GotFocus);

And add the method:

public void myTextBox_GotFocus(object sender, EventArgs e)
{
    myTextBox.SelectionLength=0;
}

I haven't tested this on C# but I ran into the same issue using a C++ WIN32 dialog box. Is seems like you can change the behavior by returning FALSE from OnInitDialog() or WM_INITDIALOG. Hope this helps.

참고URL : https://stackoverflow.com/questions/3421453/why-is-text-in-textbox-highlighted-selected-when-form-is-displayed

반응형