How do i custom draw of TEdit control text?

后端 未结 4 1482
生来不讨喜
生来不讨喜 2021-01-14 01:09

I\'d like to draw a piece of TEdit.Text using Font.Color different from the default. Are there any examples how to do that?

I\'m attempting to do something like thi

4条回答
  •  无人及你
    2021-01-14 01:32

    Some improvements to kobik solusion:

    procedure TMyEdit.Paint;
    var
      R: TRect;
      I: Integer;
    
      NewColor : TColor;
      NewBackColor : TColor;
    
      procedure DrawEx(S: String);
      begin
         if ((i-1)>=Self.SelStart) and ((i-1)<=(Self.SelStart+(Self.SelLength-1)))
            and (Self.SelLength>0) and (Self.focused)
           then begin
             Canvas.Font.Color  := clWhite;
             Canvas.Brush.Color := NewColor;
           end else begin
             Canvas.Font.Color  := NewColor;
             Canvas.Brush.Color := NewBackColor;
           end;
         Canvas.Brush.Style := bsSolid;
         DrawText(Canvas.Handle, PChar(S), -1, R, DT_LEFT or DT_NOPREFIX or
           DT_WORDBREAK or DrawTextBiDiModeFlagsReadingOnly);
      end;
    
    begin
      R := ClientRect;
      Inc(R.Left, 1);
      Inc(R.Top, 1);
      Canvas.Brush.Assign(Self.Brush);
      Canvas.Font.Assign(Self.Font);
    
      if Self.Focused then begin
          NewBackColor       := clYellow;
          Canvas.Brush.Color := NewBackColor;
          Canvas.Brush.Style := bsSolid;
          Canvas.FillRect(ClientRect);
          Canvas.DrawFocusRect(ClientRect);
        end else NewBackColor := clWhite;
    
      for I:=1 to Length(Text) do begin
       if PasswordChar=#0 then begin
         if Text[I] in ['0'..'9'] then begin
           NewColor := clRed;
           DrawEx(Text[I]);
          end else begin
           NewColor := clGreen;
           DrawEx(Text[I]);
          end;
         Inc(R.Left,Canvas.TextWidth(Text[I]));
        end else begin //with passwordchar
           NewColor := clBlack;
           DrawEx(PasswordChar);
         Inc(R.Left,Canvas.TextWidth(PasswordChar));
        end;
      end;
    end;
    

提交回复
热议问题