In RichTTextBox, I want to automatically replace emoticon strings (for example :D ) with a smiley image. I still work, except that when I write a smiley line between existing words / lines, the image is inserted at the end of the line.
For example: hello (inserting :D here) this is a message
Results: hello this is a message ☺ <Image
Another (tiny) problem is that the carriage position is set before the image after insertion.
This is what I have already received:
public class Emoticon { public Emoticon(string key, Bitmap bitmap) { Key = key; Bitmap = bitmap; BitmapImage = bitmap.ToBitmapImage(); } public string Key { get; } public Bitmap Bitmap { get; } public BitmapImage BitmapImage { get; } } public class EmoticonRichTextBox : RichTextBox { private readonly List<Emoticon> _emoticons; public EmoticonRichTextBox() { _emoticons = new List<Emoticon> { new Emoticon(":D", Properties.Resources.grinning_face) }; } protected override void OnTextChanged(TextChangedEventArgs e) { base.OnTextChanged(e); Dispatcher.InvokeAsync(Look); } private void Look() { const string keyword = ":D"; var text = new TextRange(Document.ContentStart, Document.ContentEnd); var current = text.Start.GetInsertionPosition(LogicalDirection.Forward); while (current != null) { var textInRun = current.GetTextInRun(LogicalDirection.Forward); if (!string.IsNullOrWhiteSpace(textInRun)) { var index = textInRun.IndexOf(keyword, StringComparison.Ordinal); if (index != -1) { var selectionStart = current.GetPositionAtOffset(index, LogicalDirection.Forward); if (selectionStart == null) continue; var selectionEnd = selectionStart.GetPositionAtOffset(keyword.Length, LogicalDirection.Forward); var selection = new TextRange(selectionStart, selectionEnd) { Text = string.Empty }; var emoticon = _emoticons.FirstOrDefault(x => x.Key.Equals(keyword)); if (emoticon == null) continue; var image = new System.Windows.Controls.Image { Source = emoticon.BitmapImage, Height = 18, Width = 18, Margin = new Thickness(0, 3, 0, 0) };
user5856424
source share