2012-09-08 1 views
2

목록 상자 항목에서 시각적 인 변경을 수행하여 DrawMode를 "OwnerDrawFixed"로 설정하려고합니다. 텍스트가 중간에 있도록하려는 경우 쉽게 이 수행하여 : horizentally 텍스트를 가운데에 있지만소유자 그리기 모드에서 텍스트를 가운데에 배치하는 방법

private void listTypes_DrawItem(object sender, DrawItemEventArgs e) 
{ 
    e.DrawBackground(); 
    e.Graphics.DrawString(listTypes.Items[e.Index].ToString(), 
       e.Font, Brushes.Black, e.Bounds.Left, e.Bounds.Top + e.Bounds.Height/4 
       , StringFormat.GenericDefault); 
    e.DrawFocusRectangle(); 
} 

을 내가 텍스트 폭을 알 필요가 을 얻거나 거기가 할 수있는 더 좋은 방법입니다하는 방법 당신은 코드를 시도 할 수 있습니다

답변

3

void listTypes_DrawItem(object sender, DrawItemEventArgs e) 
    { 
     ListBox list = (ListBox)sender; 
     if (e.Index > -1) 
     { 
      object item = list.Items[e.Index]; 
      e.DrawBackground(); 
      e.DrawFocusRectangle(); 
      Brush brush = new SolidBrush(e.ForeColor); 
      SizeF size = e.Graphics.MeasureString(item.ToString(), e.Font); 
      e.Graphics.DrawString(item.ToString(), e.Font, brush, e.Bounds.Left + (e.Bounds.Width/2 - size.Width/2), e.Bounds.Top + (e.Bounds.Height/2 - size.Height/2)); 
     } 
    } 
+0

감사합니다. 아마 C# 및 WindowsForms에 익숙하지 않은 사람들을 위해 약간의 설명을 추가해 주셔서 감사합니다. – Markus

2

TextRenderer.DrawText()를 사용하여 텍스트 모양이 텍스트가 양식의 다른 컨트롤에 의해 렌더링되는 방식과 일치하게해야합니다. 쉽게 만들 수 있습니다. 이미 사각형을 허용하고 그 사각형 내부에 텍스트를 가운데에 배치하는 오버로드가 있습니다. e.Bounds를 전달하십시오. 또한 선택한 항목에 다른 색을 사용하여 항목 상태에주의해야합니다. 이와 같이 :

private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { 
     e.DrawBackground(); 
     if (e.Index >= 0) { 
      var box = (ListBox)sender; 
      var fore = box.ForeColor; 
      if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) fore = SystemColors.HighlightText; 
      TextRenderer.DrawText(e.Graphics, box.Items[e.Index].ToString(), 
       box.Font, e.Bounds, fore); 
     } 
     e.DrawFocusRectangle(); 
    }