How to get the latest char written in textbox?

 ̄綄美尐妖づ 提交于 2019-12-08 16:53:21

问题


I want to know how to get the latest char written in TextBox. It does not mean the last of the string. For instance, I write this :

This i a test.

But I forgot 's', so I move my finger to the 'i' and I add the 's' :

This is a test.

So, how can I get the 's' ?

I want to get it in char or string, but I don't know how to do...

I hope it is clear.


回答1:


If you want to get the last written character, then subscribe TextBox to the KeyDown event:

C#:

textBox.KeyDown += textBox_KeyDown;

XAML:

<TextBox x:Name="textBox" KeyDown="textBox_KeyDown" />

Then:

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
    /* e.Key contains the keyboard key associated with the event. */
}

If you want to get the index of the last written character, then this is more complicated. One of the solution could be tracking the mouse position and cursor in the TextBox.




回答2:


The yBee's answer is almost correct, with the exception that event is called KeyDown, not KeyPress, at least on Windows Phone 8.




回答3:


using this code to get last character inserted in textbox

 private void Textbox1_KeyDown(object sender, KeyEventArgs e)
            {
                lastchar_inserted = e.KeyValue.ToString(); // global string variable
            }



回答4:


Have a look, it might help. To get the last character of a Text another suggestion is to append a

"\n" (nameTextbox.Append("\n"))

and then, use

int lineCount = nameTextbox.Lines.Count();

and finally, use the method

nameTextbox.GetFirstCharIndexFromLine(lineCount).

There you may have (index-1) (or Whatever, be careful and test it with a smaller text) as your last character's index.



来源:https://stackoverflow.com/questions/14939200/how-to-get-the-latest-char-written-in-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!