Freitag, 19. Juni 2009

Fill Background of a Control with Gradient

        /// <summary>

        /// Paints a gradient to the Control's background

        /// </summary>

        /// <param name="ctrl">Control that needs the brush up</param>

        /// <param name="color1">e.g. Color.FromArgb(120, 180, 255), or Color.Yellow</param>

        /// <param name="color2"></param>

        /// <param name="angle">0: horizontal, 45: top-left to bottom-right, etc.</param>

        private void PaintGradientBackground(Control ctrl, Color color1, Color color2, float angle)

        {

            Rectangle rect = new Rectangle(ctrl.Location, ctrl.Size);

 

            System.Drawing.Drawing2D.LinearGradientBrush gradBrush =

                new System.Drawing.Drawing2D.LinearGradientBrush(rect, color1, color2, angle);

 

            Bitmap bmp = new Bitmap(rect.Width, rect.Height);

 

            Graphics g = Graphics.FromImage(bmp);

            g.FillRectangle(gradBrush, rect);

 

            ctrl.BackgroundImage = bmp;

            ctrl.BackgroundImageLayout = ImageLayout.Stretch;

        }

Adding Text with different color styles in RichTextBox


/// <summary>

/// Writing to a RichTextBox in different colors should be easy enough. The intiuitional way would be:

/// richTextBox1.Text += someText;

/// richTextBox1.Select(richTextBox1.Find(someText), someText.Length);

/// richTextBox1.SelectionColor = Color.Blue;

/// Which works but gets messed up when other text is added to the RichTextBox.

/// Adding SelectedText instead of just Text does the trick:

/// </summary>

foreach (string ws in WorksheetsRequired)

{

if (this.Worksheets.ContainsKey(ws))

{

string ok = "Worksheet " + ws + " found." + Environment.NewLine;

output.SelectionColor = Color.Green;

output.SelectedText += ok;

}

else

{

string error = "Worksheet " + ws + " could not be found." + Environment.NewLine;

output.SelectionColor = Color.Red;

output.SelectedText += error;

}


// scroll to bottom of rtb
output.SelectionStart = this.richTextBox1.Text.Length;

output.ScrollToCaret();

}