简体   繁体   中英

How to get the current cursor position in NumericUpDown?

I need to get the position of the cursor in NumericUpDown to put it back the same position after triggering the focus and thousandseperator when text changed. How can I do it?

Here I can't find out oldPosition .

    void nudNofLines_KeyUp(object sender, KeyEventArgs e)
    {
        nudNofLines.Focus();
        nudNofLines.Select(oldPosition, 0);
    }

You can use the .Controls property of the NumericUpDown control to get hold of its contained controls, and from that collection get the contained TextBox.

Don't pay too much attention to me putting the line this.oldPosition = this.upDownTextBox.SelectionStart; in the KeyUp event, it was just a convenient place for me to access the SelectionStart property of the TextBox which you can use to get/set the cursor position

    public Form1()
    {
        InitializeComponent();

        var x = this.nudNofLines.Controls;
        upDownTextBox = x.OfType<TextBox>().FirstOrDefault() as TextBox;
    }

    private TextBox upDownTextBox;
    private int oldPosition;

    private void nudNofLines_KeyDown(object sender, KeyEventArgs e)
    {
        this.oldPosition = this.upDownTextBox.SelectionStart;
    }

    private void nudNofLines_KeyUp(object sender, KeyEventArgs e)
    {
        nudNofLines.Focus();
        nudNofLines.Select(oldPosition, 0);

        // Also try:
        this.upDownTextBox.SelectionStart = this.oldPosition;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM