开发者

How to get only NEW text from TextBox?

开发者 https://www.devze.com 2023-02-20 01:34 出处:网络
private void tbLog_TextChanged(object sender, TextChangedEventArgs e) { //Get only NEW text added to Log
private void tbLog_TextChanged(object sender, TextChangedEventArgs e)
{
    //Get only NEW text added to Log
}

/*
    LOG
    old message...
    old message...
    old message...
    old message...
    NEW message...
    NEW message...
    NEW message...
  开发者_如何学C  NEW message...
    NEW message...
*/  

How to I get only NEW text from the TextBox?


Perhaps you should be using the TextChangedEventArgs.Changes property:

var fullText = tbLog.Text;
if (e.Changes.Any())
{
    var additions = e.Changes.Where(tc => tc.AddedLength > 0);
    var newTexts = additions.Select(tc => fullText.Substring(tc.Offset, tc.AddedLength));

    // TODO: Do stuff with the new pieces of text
}


Something like this?

private string old_text = "";

private void tbLog_TextChanged(object sender, TextChangedEventArgs e)
{
    if(old_text != tbLog.Text)
    {
        writeLog(tbLog.Text);
        old_text = tbLog.Text;
    }
}


For desktop WPF text boxes, you should be able to use TextChangedEventArgs.Changes to enumerate the changes. Note a single event may contain several changes.

The TextChange class has Offset, AddedLength, and RemovedLength properties that give you the exact range of characters that were changed.


private void textTx1Asc_TextChanged(object sender, EventArgs e)
{                          
    string s;

    //get only the new chars
    s = textTx1Asc.Text;
    s = s.Remove(0, prev_len);          

    //update prev_len for next time
    prev_len = textTx1Asc.TextLength;

    //s contains only the new characters, process here                
}
0

精彩评论

暂无评论...
验证码 换一张
取 消