Getting the NumericUpDown value moves the carriage position, can I stop this?

I noticed that when I request a Valuecontrol NumericUpDownin a C # application, the carriage reset is at position 0. This is annoying because my application periodically captures the value of the control, so if this happens when the user enters text into it, the carriage moves unexpectedly messing with his input.

Is there a way to prevent this or a workaround? It seems that it has no property SelectionStart, otherwise I could force the polling process to keep the carriage position, get the value, and then set it as a decent workaround.

+3
source share
2 answers

I can reproduce the error with decimal point. In the tick timer event (or wherever you drag the value) try adding this code:

numericUpDown1.DecimalPlaces = 2;

numericUpDown1.Select(numericUpDown1.Value.ToString().Length, 0);

You cannot get a SelectionStart, but if you select from the end of the current row and set the parameter selection lengthto 0, it should contain the caret in the right place.

+3
source

An intermediate key blocks the text input and the cursor in the text, since getting the value will interfere with the caret position. Therefore, the iffy solution gets textboxbaseand sets the value of the caret itself.

    private void numericUpDown_KeyUp(object sender, KeyEventArgs e)
    {
        try
        {
            NumericUpDown numericUpDownsender = (sender as NumericUpDown);

            TextBoxBase txtBase = numericUpDownsender.Controls[1] as TextBoxBase;
            int currentCaretPosition = txtBase.SelectionStart;
            numericUpDownsender.DataBindings[0].WriteValue();
            txtBase.SelectionStart = currentCaretPosition;
        }
        catch (Exception ex)
        {

        }
    }
+2
source

Source: https://habr.com/ru/post/1768086/


All Articles