OwnerDraw in C #

Source: Internet
Author: User
Tags color representation constructor tostring
For controls like ComboBox, we can draw them by setting their DrawMode attributes.

For convenience, we first define a class Stringcolorobject (this has nothing to do with OwnerDraw itself, but a class written specifically for the ComboBox to be used here.) The name of the class is derived from QuickStart. The class itself is simple:



Using System.Drawing;



Namespace Ownerdrawsample

{

public class Stringcolorobject

{

field to hold the string representing the color

private string colorrepresent;

field to hold the actually color,the value of the string colorrepresent

private color color;



The constructor

Takes 2 parameters, the color representation and the color itself

Public Stringcolorobject (String Colorrepresent,color Color)

{

This.colorrepresent = colorrepresent;

This.color = color;

}



Some attributes

public string Colorrepresentation

{

Get

{

return this.colorrepresent;

}

Only Getter,no Setter

}



Public color Color

{

Get

{

return this.color;

}

Only Getter,no Setter

}



Override the ToString method in System.Object

public override string ToString ()

{

return this.colorrepresent;

}



Override the GetHashCode method

public override int GetHashCode ()

{

Return the key field ' s hash code

return This.color.GetHashCode ();

}



Override the Equals method

public override bool Equals (object obj)

{

if (!) ( obj is Stringcolorobject)

return false;

Return This.color.Equals ((stringcolorobject) obj). color);

}

}

}



Create a Windows application and drag a ComboBox from the Toolbox into the form and name it cmbcolors and add it in the form's constructor:



//

TODO: Add any constructor code after the InitializeComponent call

//

This. Fillcomboxcolor (this.cmbcolors);

This.cmbColors.SelectedIndex = 0;



where Fillcomboxcolor (ComboBox) is a custom function that populates the ComboBox object specified by the parameter. Its implementation is:

private void Fillcomboxcolor (ComboBox CMB) {

Cmb. Items.addrange (New object[]{

New Stringcolorobject ("Black", Color.Black),

New Stringcolorobject ("Blue", Color.Blue),

New Stringcolorobject ("Crimson (Dark Red)", color.darkred),

New Stringcolorobject ("green", Color.green),

......

});

}

It's just some prep work, and OwnerDraw's actual work is just beginning. Sets the DrawMode of the ComboBox object Cmbcolors to OwnerDrawFixed (or ownerdrawvariable, This is set to OwnerDrawFixed mode). Incidentally: DrawMode can take normal,ownerdrawfixed and ownerdrawvariable one of the three. The normal pattern indicates that the control is drawn by the operating system. And the elements are equal in size; the ownerdrawfixed pattern represents that the control is drawn by hand and the element is of equal size, while ownerdrawvariable indicates that the control is drawn by hand and that the size of the element can be unequal.



Below begins the OwnerDraw of the core section:

1 Compose the control's MeasureItem event

This event is first evoked when you want to display an item of ComboBox [that is, when you click the ComboBox drop-down Button]. It is used to measure item length, width information. For example:

Registering events

This.cmbColor.MeasureItem + = new Measureitemeventhandler (This.cmbcolor_measureitem);

Implement Cmbcolor_measureitem---Measure each item of ComboBox

private void Cmbcolor_measureitem (object sender, System.Windows.Forms.MeasureItemEventArgs e)

{

Generally, you need to set the ItemHeight and Itemwidth properties of the MeasureItemEventArgs object E

ComboBox CMB = (ComboBox) sender;

E.itemheight = CMB. itemheight;//of course, you can write E. ItemHeight = 20;

For ownerdrawfixed mode, however, this function seems to be superfluous. (So for ComboBox)

WHY????????????? More WORK is essential.

}



2 Compose the control's DrawItem event

The drawing task for the items in ComboBox will be completed in the DrawItem event. Similarly, register the event before adding the appropriate code to complete the response to the event:

Registering events

This.cmbColor.DrawItem + = new

Drawitemeventhandler (This.cmbcolor_drawitem);

Draw Item

private void Cmbcolor_drawitem (object sender, System.Windows.Forms.DrawItemEventArgs e)

{

ComboBox CMB = (ComboBox) sender;

if (CMB = null) return;

int index = E.index; Gets the index (index) of the item to be drawn

if (index = = 1) return;

If Item is selected, draw the correct background color

E.drawbackground ();

E.drawfocusrectangle ();//Because item is selected, draw the focus rectangle



Graphics g = e.graphics;

Gets the corresponding color based on the item's index

Color C = ((Stringcolorobject) Cmbcolor.items[index]). Color;

Rectangle Rectcolor = e.bounds;//Gets the bounding rectangle that surrounds the item and stores it in Rectcolor

The proper transformation of the rectcolor does not affect the E. Bounds itself

Rectcolor.offset (2,2)//Move right 2, Move down 2

Rectcolor.width = 20;//width set to 20

Rectcolor.height-= 4;//height minus 4

G.drawrectangle (New Pen (c), rectcolor);//Draw the rectangle represented by the Rectcolor, that is, the rectangular portion to the left of the item seen in the figure



Once again, the Rectcolor is transformed and populated

Rectcolor.offset (2,2);

Rectcolor.width = 17;//to note that drawing and populating in C #

Rectcolor.height-= 3;//different handling of the last pixel point

G.fillrectangle (New SolidBrush (c), Rectcolor)//fills the Rectcolor rectangle, which is the filled rectangle to the left of the item seen in the figure



g.DrawString (((stringcolorobject) Cmbcolor.items[index]). ToString (),

This. Font,new SolidBrush (c), E.bounds.left + 25,e.bounds.top);

Drawing strings

}



This program will work very well. To be able to read the program, you need to know some of the following concepts:

1. The index attribute of the E.index MeasureItemEventArgs object is the meaning of the indexed value of the item to be drawn. For the example above, black, blue ... respectively corresponding to the index of the 0,1 ... (This is not very strict, but it is easy to accept.) The more rigorous argument is that the Stringcolorobject object corresponds to the index ...).

2. E.graphics This is the Graphics object that you want to draw on the item. With it, you can achieve the drawing of the graph on item.

3). E.bounds This is the bounding rectangle of the item to draw.


Knowing these concepts, it is not difficult to understand what the above drawitem is doing and why it is done that way.



For MenuItem hand-drawn, you have to do the same thing as above. The difference is that you need to set its OwnerDraw to True by default false. And then Measureitem,drawitem. If you're hands-on, You will find that if you do not register MeasureItem and code, you will not see that MenuItem.



---the end





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.