如何捕获文本框中的光标位置?

问题描述:

我在我的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? 
     } 
    } 

SOLUTION

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

通过游标,你的意思是鼠标? – sTrenat

+0

我的意思是在你输入文本框时显示的光标。 “|”光标。 –

您可以使用myTextBox.CaretIndex

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

谢谢,它工作。 –