gpt4 book ai didi

delphi - 如何自定义绘制 TEdit 控件文本?

转载 作者:行者123 更新时间:2023-12-03 15:15:05 29 4
gpt4 key购买 nike

我想使用与默认不同的 Font.Color 绘制一段 TEdit.Text。有没有例子如何做到这一点?

我正在尝试做这样的事情:

注意:这张截图只是一个毛茸茸的草稿,但它让我相信什么问题是可以解决的。

最佳答案

Edit 控件不支持所有者绘制,但您可以通过子类化它并处理自定义绘制它>WM_PAINT(以及许多其他消息)。这是可行的,但实际 100% 正确实现将是一个痛苦的世界。来自文档:Developing Custom Draw Controls in Visual C++ :

Note that owner-draw will work for most controls. However, it doesn't work for edit controls; and with regards to the list control, it works only for report-view style

我也很想知道兔子洞到底有多深,所以,
这是使用插入器类的代码示例(仍然需要实现选择,但当插入符位于控件中时自定义绘图可以工作):

type
TEdit = class(StdCtrls.TEdit)
private
FCanvas: TCanvas;
procedure WMPaint(var Message: TWMPaint); message WM_PAINT;
protected
procedure WndProc(var Message: TMessage); override;
procedure Paint; virtual;
procedure PaintWindow(DC: HDC); override;
property Canvas: TCanvas read FCanvas;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;

...

constructor TEdit.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCanvas := TControlCanvas.Create;
TControlCanvas(FCanvas).Control := Self;
end;

destructor TEdit.Destroy;
begin
FCanvas.Free;
inherited Destroy;
end;

procedure TEdit.Paint;
var
R: TRect;
I: Integer;
S: String;
begin
R := ClientRect;
Inc(R.Left, 1);
Inc(R.Top, 1);
Canvas.Brush.Assign(Self.Brush);
Canvas.Font.Assign(Self.Font);
for I := 1 to Length(Text) do
begin
if Text[I] in ['0'..'9'] then
Canvas.Font.Color := clRed
else
Canvas.Font.Color := clGreen;
S := Text[I];
DrawText(Canvas.Handle, PChar(S), -1, R, DT_LEFT or DT_NOPREFIX or
DT_WORDBREAK or DrawTextBiDiModeFlagsReadingOnly);
Inc(R.Left,Canvas.TextWidth(S));
end;
end;

procedure TEdit.PaintWindow(DC: HDC);
begin
FCanvas.Lock;
try
FCanvas.Handle := DC;
try
TControlCanvas(FCanvas).UpdateTextFlags;
Paint;
finally
FCanvas.Handle := 0;
end;
finally
FCanvas.Unlock;
end;
end;

procedure TEdit.WMPaint(var Message: TWMPaint);
begin
ControlState := ControlState+[csCustomPaint];
inherited;
ControlState := ControlState-[csCustomPaint];
end;

procedure TEdit.WndProc(var Message: TMessage);
begin
inherited WndProc(Message);
with Message do
case Msg of
CM_MOUSEENTER, CM_MOUSELEAVE, WM_LBUTTONUP, WM_LBUTTONDOWN,
WM_KEYDOWN, WM_KEYUP,
WM_SETFOCUS, WM_KILLFOCUS,
CM_FONTCHANGED, CM_TEXTCHANGED:
begin
Invalidate;
end;
end;
end;

enter image description here

关于delphi - 如何自定义绘制 TEdit 控件文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9758016/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com