private void pbPaletteCode_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; g.FillRectangle(Brushes.White, 0, 0, 1000, 1000); Font f = new Font("Courier New", 8); int nLineHeight = (int)f.GetHeight(); int nTabIndent = 15; int nY = 0; int nX = 0; g.DrawString(String.Format("const unsigned short int Palette[] = {{"), f, Brushes.Black, 0, nY); // Aaaargh! All we want to do here is measure the width of the 3 string segments: // 0x0000; // aabbbbc // so a = width of "0x", b = width of "0000" and c = width = of ";". // // MeasureString seems perfect for this: // PointF ptOrigin = new PointF(0.0f, 0.0f); // int nWidth0 = (int)g.MeasureString("0x", f, ptOrigin, StringFormat.GenericTypographic).Width; // int nWidth1 = (int)g.MeasureString("0000", f, ptOrigin, StringFormat.GenericTypographic).Width; // int nWidth2 = (int)g.MeasureString(",", f, ptOrigin, StringFormat.GenericTypographic).Width; // except that it doesn't return the correct size. // // Fortunately, MeasureCharacterRanges does return the correct size, but it require significantly more // work to set up. string strTemplate = "0x0000;"; // We assume that all numbers in the font are the same width CharacterRange[] charanges = { new CharacterRange(0, 2), new CharacterRange(2, 4), new CharacterRange(6, 1), }; RectangleF rLayout = new RectangleF(0.0f, 0.0f, 100.0f, 100.0f); StringFormat sformat = new StringFormat(); sformat.SetMeasurableCharacterRanges(charanges); Region[] sregions = new Region[3]; sregions = g.MeasureCharacterRanges(strTemplate, f, rLayout, sformat); int nWidth0 = (int)sregions[0].GetBounds(g).Width; int nWidth1 = (int)sregions[1].GetBounds(g).Width; int nWidth2 = (int)sregions[2].GetBounds(g).Width; int nWidthTotal = nWidth0 + nWidth1 + nWidth2; nX = nTabIndent; nY += nLineHeight; for (int i = 0; i < 8; i++) { if (m_subpalette.CurrentColor == i) { g.DrawRectangle(Pens.Red, nX + 1 + nWidth0, nY + 1, nWidth1, nLineHeight); } g.DrawString(String.Format("0x{0:x4},", m_subpalette.Encoding(i)), f, Brushes.Black, nX, nY); nX += nWidthTotal; } nY += nLineHeight; nX = nTabIndent; for (int i = 0; i < 8; i++) { if (m_subpalette.CurrentColor == i + 8) { g.DrawRectangle(Pens.Red, nX + 1 + nWidth0, nY + 1, nWidth1, nLineHeight); } g.DrawString(String.Format("0x{0:x4},", m_subpalette.Encoding(8 + i)), f, Brushes.Black, nX, nY); nX += nWidthTotal; } nY += nLineHeight; g.DrawString(String.Format("}};"), f, Brushes.Black, 0, nY); }