1

I insert images into RichTextBox from app resources. Image format PNG, background is transparent. After insert, background of image is gray. How i can set background of image to transparent?

enter image description here

My current code:

private Hashtable icons = null;

private void LoadIcons()
{
   icons = new Hashtable(3);
   icons.Add("[inf]", Properties.Resources.inf);
   icons.Add("[ok]", Properties.Resources.ok);
   icons.Add("[err]", Properties.Resources.err);
}

private void SetIcons()
{
   richTextBox.ReadOnly = false;
   foreach (string icon in icons.Keys)
   {
      while (richTextBox.Text.Contains(icon))
      {
         IDataObject tmpClibboard = Clipboard.GetDataObject();
         int index = richTextBox.Text.IndexOf(icon);
         richTextBox.Select(index, icon.Length);
         Clipboard.SetImage((Image)icons[icon]);
         richTextBox.Paste();
         Clipboard.SetDataObject(tmpClibboard);
      }
   }
   richTextBox.ReadOnly = true;
}

private void richTextBox_TextChanged(object sender, EventArgs e)
{
   SetIcons();
}
DaddyRatel
  • 729
  • 3
  • 13
  • 30
  • Create another bitmap of the same size. Use Graphics.FromImage(), Graphics.Clear() to set the background color you want (like richTextBox.BackColor), Graphics.DrawImage() to draw the image. Do note that allowing the user to edit the text in the RTB isn't a great idea. Set ReadOnly = true and your problem disappears. – Hans Passant Apr 18 '14 at 11:17

2 Answers2

1

I have the same problem and my solution was to create new empty bitmap with your icon size and then set its background to richtextbox background color. After that, I drawed with graphics object the icon on the previous bitmap.

Here's the code:

Create a bitmap with the size of your icon (here, warning from ressource file)

Bitmap img = new Bitmap(Icons.warning.Width, Icons.warning.Height);

Create graphic object from this bitmap

Graphics graphics = Graphics.FromImage(img);

Set the background of the bitmap on richtextbox background

graphics.Clear(richTextBox.BackColor);

Then overlay your icon on the bitmap

graphics.DrawImage(Icons.warning,Point.Empty);

ps: Sorry for my bad english ;)

Peace :)

Papapinguy
  • 41
  • 5
0

There is no such thing as true transparency in a WinForms Control. Transparent mode inherits the default background of its parent. The way I have worked around it in the past has been to use the OnPaint event and then use the Graphics.DrawString method to position the text where I want it.

Try

Alpha blend controls

coder
  • 13,002
  • 31
  • 112
  • 214
  • I change part of `LoadIcons()` to `Bitmap bmp = Properties.Resources.inf; bmp.MakeTransparent(Color.FromArgb(211, 211, 211)); icons.Add("[inf]", bmp);` but it's nothing change background for this image. – DaddyRatel Apr 18 '14 at 07:27
  • try this http://stackoverflow.com/questions/1946139/how-to-change-the-background-color-of-a-rich-text-box-when-it-is-disabled – coder Apr 18 '14 at 07:34