TreeViewのテキストの右側に文字を書く

拙作返信屋2007では、メールフォルダ名の右側に未読メールの数を表示している。これを実現するためには、OnCutomDrawItemイベントで簡単にできそうである。


procedure TForm1.TreeView1CustomDrawItem(Sender: TCustomTreeView;
  Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean);
var
  Rect: TRect;
begin
  if (Node = nil) or Node.Deleting then
    Exit;

  Rect := Node.DisplayRect(True);
  TreeView1.Canvas.TextOut(Rect.Right + 4, Rect.Top + 2, 'RightWrite');
end;

だが、これはうまくいかない。Nodeを選択すると"RightWrite"まで選択されてしまう。Canves.TextOutで書くと、そのテキストもNodeのテキストとなるようだ。それより問題なのは、そもそもNodeテキストの表示がおかしくなることだ。どうしてこうなるのかわからなかったのでWindowsAPIを使って以下のように書いた。


procedure TForm1.TreeView1CustomDrawItem(Sender: TCustomTreeView;
  Node: TTreeNode; State: TCustomDrawState; var DefaultDraw: Boolean);
var
  Rect: TRect;
  dc: THandle;
  S: string;
begin
  if (Node = nil) or Node.Deleting then
    Exit;

  dc := GetDC(Node.Handle);
  try
    Rect := Node.DisplayRect(True);
    SetTextColor(dc, ColorToRGB(clBlue));
    SelectObject(dc, TreeView1.Font.Handle);
    S := 'RightWrite';
    Windows.TextOut(dc, Rect.Right + 4, Rect.Top + 2, PChar(S), Length(S));
  finally
    ReleaseDC(Node.Handle, dc);
  end;
end;

Tips

ブログ

リンク