-1

I am using visual c# to create a windows chat app, and I want all the :) words inside the chatDisplay rich text box to be replaced with a smiley image located in the resources folder. this is my code:

private void add_smileys()
{
    if (chatDisplay.Text.Contains(":)"))
    {
        chatDisplay.SelectionStart = chatDisplay.Find(":)", RichTextBoxFinds.WholeWord);
        chatDisplay.SelectionLength = 2;

        String image = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "Resources/smile.png");
        Image img = Image.FromFile(image);
        Clipboard.SetImage(img);
        chatDisplay.Paste();
        Console.WriteLine("All images replaced");
    }
}

I don't get any errors, and I don't get the "file not found" error either, and the "All images replaced" center is outputted in the console correctly. the only wrong thing is that the :) phrase in the textbox doesn't get replaced with the image. can someone help me? what's wrong with my code?

dub stylee
  • 3,252
  • 5
  • 38
  • 59
Othuna
  • 129
  • 1
  • 12

1 Answers1

0

Here a sample code for a single emoticon :) You may extend it for all emoticons as you need.

private void richTextBoxOutput_TextChanged(object sender, EventArgs e)
{
    UpdateEmoticon();
}

private void UpdateEmoticon(int startIndex = 0)
{
    const string smileKey = ":)";
    const int smileKeyLen = 2;

    DataFormats.Format myFormat = DataFormats.GetFormat(DataFormats.Bitmap);
    var index = richTextBoxOutput.Find(smileKey, startIndex, RichTextBoxFinds.None);
    if (index == -1)
        return;

    richTextBoxOutput.Select(index, smileKeyLen);

    using (var bmp = new Bitmap(Resources.smile))
    {
        Clipboard.SetDataObject(bmp);

        if (richTextBoxOutput.CanPaste(myFormat))
        {
            richTextBoxOutput.Paste(myFormat);
        }
    }

    UpdateEmoticon(startIndex + smileKeyLen);
}
denys-vega
  • 3,522
  • 1
  • 19
  • 24