Beautify the WinForm control by using the redrawing item
If you think that the ComboBox, ListBox, or other Winforms controls in the project cannot meet your display requirements, many controls, including forms, support redrawing and modifying the display style. The following example Re-draws the ComBox data items, hoping to play a leading role.
Displays the source code using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Linq;
Using System. Text;
Using System. Windows. Forms;
Namespace SimpleDemo
{
Public partial class frmDrawItem: Form
{
Public frmDrawItem ()
{
InitializeComponent ();
// Specify the painting mode. This parameter must be set to OwnerDrawFixed and OwnerDrawVariable.
// Normal is drawn by the operating system, and the element sizes are equal.
// The OwnerDrawFixed is manually drawn and the element size is equal.
// The OwnerDrawVariable can be manually drawn, and the element size may not be equal.
ComboBox2.DrawMode = DrawMode. OwnerDrawFixed;
}
// Redraw item event
Private void comboBox2_DrawItem (object sender, DrawItemEventArgs e)
{
// Obtain the graphic surface on which you want to draw items
Graphics g = e. Graphics;
// Obtain the rectangle representing the boundary of the drawn item
System. Drawing. Rectangle rect = e. Bounds;
// Define the icon image to be drawn to the control
Image ico = Image. FromFile ("head.png ");
// Define the font object
System. Drawing. Font font = new System. Drawing. Font (new FontFamily (""), 12 );
If (e. Index> = 0)
{
// Obtain the text of the current Item
String tempString = comboBox2.Items [e. Index]. ToString ();
// If the current item is a normal item with no status
If (e. State = DrawItemState. None)
{
// Draw a rectangle on the surface of the current item.
G. FillRectangle (new SolidBrush (Color. FromArgb (200,230,255), rect );
// Mark the current item on the graph Surface
G. DrawImage (ico, new Point (rect. Left, rect. Top ));
// Draw the text of the current Item on the current Item graph Surface
G. DrawString (tempString, font, new SolidBrush (Color. Black), rect. Left + ico. Size. Width, rect. Top );
// Draw the focus box
E. DrawFocusRectangle ();
}
Else
{
E. Graphics. FillRectangle (new SolidBrush (Color. LightBlue), rect );
G. DrawImage (ico, new Point (rect. Left, rect. Top ));
G. DrawString (tempString, font, new SolidBrush (Color. Black), rect. Left + ico. Size. Width, rect. Top );
E. DrawFocusRectangle ();
}
}
}
}
}
Conclusion: You can choose to use skin controls for beautification, but the re-painting method is more flexible and can meet some functional requirements. In addition, there are some different re-painting events for different controls. You can refer to MSDN.