【问题标题】:How to capture the cursor position in a textbox?如何捕获文本框中的光标位置?
【发布时间】:2019-03-21 02:15:05
【问题描述】:

我的 Masked TextBox 上有一个 TextChanged 事件,我希望在光标停留在末尾时调用它的方法。

例如:

222.222.2/21

一旦用户输入“1”,该事件就会被调用。

XAML

<TextBox
                Name="myTextBox"
                ToolTip="type here"
                Height="30"
                Width="100"
                FontSize="14"
                MaxLength="12"
                HorizontalContentAlignment="Right"
                TextChanged="MyMethod"/>

C#

 private void MyMethod(object sender, EventArgs e){
     if (myTextBox.Text.Length == myTextBox.MaxLength)
        {
            //how do I know if the cursor is at the end?
        }
    }

解决方案

private void MyMethod(object sender, EventArgs e){
     if (myTextBox.Text.Length == myTextBox.MaxLength)
        {
            if(process.CaretIndex == 12)
            {
               //do something
            }
        }
    }

【问题讨论】:

  • 光标是指鼠标?
  • 我的意思是当你在文本框中输入时显示的光标。 “|”光标。

标签: c# wpf xaml events textbox


【解决方案1】:

您可以使用myTextBox.CaretIndex

private void MyMethod(object sender, EventArgs e)
{
    if (myTextBox.Text.Length == myTextBox.MaxLength)
    {
        System.Diagnostics.Debug.WriteLine($"caret is at {myTextBox.CaretIndex}");
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多