簡體   English   中英

如何在NumericUpDown中獲取當前光標位置?

[英]How to get the current cursor position in NumericUpDown?

我需要在 NumericUpDown 中獲取光標的位置,以便在文本更改時觸發焦點和千位分隔符后將其放回相同的位置。 我該怎么做?

在這里我找不到oldPosition

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

您可以使用 NumericUpDown 控件的.Controls屬性來獲取其包含的控件,並從該集合中獲取所包含的 TextBox。

不要太注意我把this.oldPosition = this.upDownTextBox.SelectionStart; 在 KeyUp 事件中,它只是一個方便我訪問 TextBox 的 SelectionStart 屬性的地方,您可以使用它來獲取/設置光標位置

    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;

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM