Link to home
Start Free TrialLog in
Avatar of rwinkler
rwinkler

asked on

custom Listbox double buffering

I'm using a custom listbox (which uses System.Windows.Forms.ListBox) and am trying to double buffer it in order to stop the accursed flicker.  My test case uses 4 different items in the list.  In OnDrawItem, I create a new Bitmap of the appropriate size and then create a Graphics from the Bitmap.  Then I "draw" the correct string from the event.  Finally, I draw the Bitmap to the ListBox and then dispose of the graphics objects and bitmap (I've tried without disposing them, with the same results).  Only the first item gets drawn.  Debug.WriteLine code tells me that OnDrawItem is getting called with the appropriate values (text, x & y location, etc.).  As a last ditch effort, I put code into the OnDrawItem that looped through all 4 items, drawing each one.  This resulted in 4 items getting drawn, all with the same, first value (and the expected issues involving improper invalidation... it was just a test, after all).  What have I done wrong?  Who did I wrong in a past life?

protected override void OnDrawItem(DrawItemEventArgs e)
{
base.OnDrawItem(e);
// Verify index is valid before painting
if (e.Index >= 0)
{
for(int i=0;i<4;i++)
{
    Bitmap bmp = GetIndexBitmap(i);//e.Index);
    Graphics graphics = CreateGraphics();
    graphics.DrawImage(bmp, e.Bounds.X, e.Bounds.Y);
    //Debug.WriteLine("index:"+e.Index+"  x="+rectItem.X+"  y="+rectItem.Y);
    graphics.Dispose();
    bmp.Dispose();
  }
}
}


protected Bitmap GetIndexBitmap(int nIndex)
{
Rectangle r = GetItemRectangle(nIndex);
Bitmap offScreenBmp = new Bitmap(r.Width, r.Height);
Graphics offScreenDC = Graphics.FromImage(offScreenBmp);
string sItemText = (string)Items[nIndex];
Debug.WriteLine("index:"+nIndex+"  Items[index]:"+Items[nIndex]+"  str="+sItemText);

pCurrentBrush = m_NormalTextSolidBrush;

// Clear the background for fresh drawing
//offScreenDC.FillRectangle(m_BackSolidBrush, e.Bounds);

// Draw text
{
  offScreenDC.DrawString(sItemText, Font, pCurrentBrush, (float)(r.Left + m_nIndentLeft),(float)(r.Top + m_nIndentTop));
}

Rectangle rectItem = GetItemRectangle(nIndex);
offScreenDC.DrawImage(offScreenBmp, r.X, r.Y);
offScreenDC.Dispose();
return offScreenBmp;
}

}
}
ASKER CERTIFIED SOLUTION
Avatar of rama_krishna580
rama_krishna580
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Oops the commented lines are not necessary... ;o)