简体   繁体   中英

How to get only NEW text from TextBox?

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...
    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                
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM