View Single Post
 
Old 10-13-2005, 06:41 AM
Iceplug's Avatar
Iceplug Iceplug is offline
MetaCenturion

Retired Moderator
* Guru *
 
Join Date: Aug 2001
Location: Iowa, USA
Posts: 16,583
Smile OwnerDraw on Listboxes

OwnerDraw for listboxes is fairly similar to OwnerDraw for menus.

You use MeasureItem to get the size, and then DrawItem to draw the new element within the listbox.

A difference with the listbox however is that, to set the OwnerDraw properties of the listbox, you have to set the DrawMode of the listbox, in contrast to the OwnerDraw property of the menu component.

The DrawMode property of the listbox supports two OwnerDraw modes: OwnerDrawFixed and OwnerDrawVariable

OwnerDrawFixed

OwnerDrawFixed means that you cannot specify the size of the item within the listbox... this means that you don't even have to bother with the MeasureItem event and you can go directly to DrawItem. The items are all regular-size.

So, in the DrawItem, you draw the listbox items:
Code:
Private Sub LB_DrawItem(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DrawItemEventArgs) Handles LB.DrawItem e.DrawBackground() If e.Index >= 0 Then e.Graphics.DrawString(LB.Items(e.Index).ToString(), LB.Font, Brushes.Black, e.Bounds.X, e.Bounds.Y) End If End Sub
You will need the If e.Index >= 0 Then line if you are planning to remove things from the listbox.

Again, it's a graphics object, so you can draw whatever you need.

If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
to check this listbox item's state.

e.DrawBackground() draws the regular background for regular listboxes.

You can make your own by checking the state property.
Code:
If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then e.Graphics.FillRectangle(Brush2, e.Bounds) Else e.Graphics.FillRectangle(Brush1, e.Bounds) End If

OwnerDrawVariable
This one lets you set the height of the entry within the listbox. So, you must handle the MeasureItem event for Listboxes that have a DrawMode of OwnerDrawVariable.

The drawings are made the same way:
Code:
If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then e.Graphics.FillRectangle(Brush2, e.Bounds) Else e.Graphics.FillRectangle(Brush1, e.Bounds) End If

And that's it.

Check out the attachment below - I have a listbox with a background image on it and a listbox that lists the fonts drawn in their own font, just like in MS Word (except with a listbox instead of a combobox).
Attached Files
File Type: zip Overdos2.zip (35.4 KB, 135 views)
__________________

Iceplug, USN
Quadrill 1 Quadrill 2 (full) Quadrill 3 JumpCross .NET Website is ALIVE! - DL Platform Tour for VB.NET! Posting Guidelines Hint: Specify your location in your user cp profile if you want compassion!
Reply With Quote