下面的示例代码演示了如何绘制自定义文本以响应发送到 ComboBox 控件父窗口的WM_DRAWITEM 消息(这应该是示例工作的表单,否则子类化控件或完整绘制控制是必要的)。
要接收此消息,请将控件的Style 属性设置为“csOwnerDrawFixed”,但不要为OnDrawItem 事件设置处理程序,以便在我们干预绘图的所有其他情况下应用默认绘图。
当ItemIndex 为-1 时,该示例设置了一个文本,但可以在其他情况下对其进行调整/调整。请注意,绘图代码不完整或不准确,示例只是演示了一种方法:
type
TForm1 = class(TForm)
ComboBox1: TComboBox;
[..]
private
procedure WMDrawItem(var Msg: TWMDrawItem); message WM_DRAWITEM;
end;
[...]
procedure TForm1.WMDrawItem(var Msg: TWMDrawItem);
var
Font: HFONT;
begin
inherited;
if (Msg.Ctl = ComboBox1.Handle) and (Msg.DrawItemStruct.itemID = $FFFFFFFF) and
((Msg.DrawItemStruct.itemAction and ODA_DRAWENTIRE) = ODA_DRAWENTIRE) then begin
Font := SelectObject(Msg.DrawItemStruct.hDC, ComboBox1.Canvas.Font.Handle);
SelectObject(Msg.DrawItemStruct.hDC, GetStockObject(DC_BRUSH));
if (Msg.DrawItemStruct.itemState and ODS_SELECTED) = ODS_SELECTED then begin
SetDCBrushColor(Msg.DrawItemStruct.hDC, ColorToRGB(clHighlight));
SetBkColor(Msg.DrawItemStruct.hDC, ColorToRGB(clHighlight));
SetTextColor(Msg.DrawItemStruct.hDC, ColorToRGB(clHighlightText));
end else begin
SetDCBrushColor(Msg.DrawItemStruct.hDC, ColorToRGB(clWindow));
SetBkColor(Msg.DrawItemStruct.hDC, ColorToRGB(clWindow));
SetTextColor(Msg.DrawItemStruct.hDC, ColorToRGB(clWindowText));
end;
FillRect(Msg.DrawItemStruct.hDC, Msg.DrawItemStruct.rcItem, 0);
TextOut(Msg.DrawItemStruct.hDC, 4, 4, '_no_selected_item_', 18);
SelectObject(Msg.DrawItemStruct.hDC, Font);
end;
end;