cómo añadir emoticonos (smileys) en WPF RichTextBox
-
01-10-2019 - |
Pregunta
Tengo una ventana de chat IM WPF con un cuadro de texto de entrada y salida de un cuadro de texto enriquecido. Quiero representar el texto de entrada en el cuadro de texto enriquecido. Cuando el usuario introduce un símbolo smiley :) como en el bloque de texto con algunos textos, quiero reemplazar sonriente que con predefinido sonriente imagen de texto y hacer que en el cuadro de texto enriquecido. Es muy similar a GTalk comportamiento de la ventana de chat.
¿Cómo puedo hacer esto? gracias de antemano: -)
Solución
Se puede utilizar esta función emoticonos a continuación:
#region add emotion to RichTextBox function
private Dictionary<string, string> _mappings = new Dictionary<string, string>();
private string GetEmoticonText(string text)
{
string match = string.Empty;
int lowestPosition = text.Length;
foreach (KeyValuePair<string, string> pair in _mappings)
{
if (text.Contains(pair.Key))
{
int newPosition = text.IndexOf(pair.Key);
if (newPosition < lowestPosition)
{
match = pair.Key;
lowestPosition = newPosition;
}
}
}
return match;
}
// And also function which add smiles in richtextbox, here is it:
private void Emoticons(string msg,Paragraph para )
{
//try
//{
// Paragraph para = new Paragraph { LineHeight = 1 };
Run r = new Run(msg);
para.Inlines.Add(r);
string emoticonText = GetEmoticonText(r.Text);
//if paragraph does not contains smile only add plain text to richtextbox rtb2
if (string.IsNullOrEmpty(emoticonText))
{
rtbConversation.Document.Blocks.Add(para);
}
else
{
while (!string.IsNullOrEmpty(emoticonText))
{
TextPointer tp = r.ContentStart;
// keep moving the cursor until we find the emoticon text
while (!tp.GetTextInRun(LogicalDirection.Forward).StartsWith(emoticonText))
tp = tp.GetNextInsertionPosition(LogicalDirection.Forward);
// select all of the emoticon text
var tr = new TextRange(tp, tp.GetPositionAtOffset(emoticonText.Length)) { Text = string.Empty };
//relative path to image smile file
string path = _mappings[emoticonText];
Image image = new Image
{
Source =
new BitmapImage(new System.Uri(Environment.CurrentDirectory+path,
UriKind.RelativeOrAbsolute)),
Width = Height = 25,
};
//insert smile
new InlineUIContainer(image, tp);
if (para != null)
{
var endRun = para.Inlines.LastInline as Run;
if (endRun == null)
{
break;
}
else
{
emoticonText = GetEmoticonText(endRun.Text);
}
}
}
rtbConversation.Document.Blocks.Add(para);
}
}
// ///
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_mappings.Add(@"s-]", "/Images/smiley/silly.png");
_mappings.Add(@":-|", "/Images/smiley/angry.png");
}
//Call function to use
private void SendMessage(object sender,RoutedEventArgs e)
{
Paragraph paragraph = new Paragraph();
paragraph.LineHeight = 1;
Run name = new Run();
name.Text =rtbMessage.Text+ " : ";
name.Foreground = new SolidColorBrush(Colors.Red);
paragraph.Inlines.Add(new Bold(name));
//paragraph.Inlines.Add(new Run(name.text));
rtbConversation.Document.Blocks.Add(paragraph);
Emoticons(name.Text, paragraph);
rtbConversation.ScrollToEnd();
}
Otros consejos
Esto sería así
Viendo texto de la imagen en línea con
y el uso de código detrás de archivo que puede hacer lo mismo
//Create a new RichTextBox.
RichTextBox MyRTB = new RichTextBox();
// Create a Run of plain text and image.
Run myRun = new Run();
myRun.Text = "Displaying text with inline image";
Image MyImage = new Image();
MyImage.Source = new BitmapImage(new Uri("flower.jpg", UriKind.RelativeOrAbsolute));
MyImage.Height = 50;
MyImage.Width = 50;
InlineUIContainer MyUI = new InlineUIContainer();
MyUI.Child = MyImage;
// Create a paragraph and add the paragraph to the RichTextBox.
Paragraph myParagraph = new Paragraph();
MyRTB.Blocks.Add(myParagraph);
// Add the Run and image to it.
myParagraph.Inlines.Add(myRun);
myParagraph.Inlines.Add(MyUI);
//Add the RichTextBox to the StackPanel.
MySP.Children.Add(MyRTB);
Esto no es fácil. Enfoque general sería controlar rico cuadro de texto de entrada, encontrar todos los emoticonos y reemplazarlos con imágenes: Run
descanso donde encontró una sonrisa en Span
con Runs
y Images
. Por ejemplo.
<RichTextBox>
<FlowDocument>
<Paragraph>
<!-- Before -->
<Run>Hello :) world!</Run>
<!-- After -->
<Span>
<Run Text="Hello"/>
<Image Width="16" Source="http://kolobok.us/smiles/light_skin/smile.gif"/>
<Run Text=" world"/>
</Span>
</Paragraph>
</FlowDocument>
</RichTextBox>
Espero que esto ayude.
Hay un artículo que ayuda a crear un editor extendida.
http://www.codeproject.com/Tips/599014/ WPF-RichTextBox-soporte-smileys