我有一个程序,底部有一个包含三个元素的状态栏.我想用不同的字体颜色重绘第二个元素,以表示用户有效.我的问题的第一部分是: a)如何以不同的颜色将文本重绘为默认文本? 和b)如何
a)如何以不同的颜色将文本重绘为默认文本?
和b)如何在触发事件后以不同的颜色绘制文本(例如按下按钮)?
我目前的代码如下.我正在尝试检查以不同颜色重新绘制面板的条件是否正确(CurrentUser.Valid,这是一个布尔值),然后尝试重新着色文本.这目前不起作用.
procedure TChatFormMain.sbarMainDrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); var RectForText: TRect; begin if (Panel = StatusBar.Panels[1]) and (CurrentUser.Valid) then begin sbarMain.Canvas.Font.Color := clGreen; RectForText := Rect; StatusBar.Canvas.FillRect(RectForText); DrawText(sbarMain.Canvas.Handle, PChar(Panel.Text), -1, RectForText, DT_SINGLELINE or DT_VCENTER or DT_LEFT); end; end;
在代码的另一部分,我正在调用StatusBar.repaint;尝试用新文本颜色重新绘制条形图,这是正确的吗?
更新MCVE:
unit colourStatusU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls; type TForm1 = class(TForm) StatusBar1: TStatusBar; Button1: TButton; procedure Button1Click(Sender: TObject); procedure StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); private { Private declarations } public { Public declarations } end; var Form1: TForm1; valid : boolean; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); begin valid := true; StatusBar1.Repaint; end; procedure TForm1.StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); var RectForText: TRect; begin if (Panel = StatusBar.Panels[1]) and (Valid) then begin Canvas.Font.Color := clGreen; RectForText := Rect; Canvas.FillRect(RectForText); DrawText(Canvas.Handle, PChar(Panel.Text), -1, RectForText, DT_SINGLELINE or DT_VCENTER or DT_LEFT); end; end; end.OnDrawPanel事件仅针对其Style设置为psOwnerDraw的面板调用,因此请确保在Object Inspector或代码中正确设置了Style.
要绘制的画布必须是TStatusBar.Canvas,但您使用的是TForm.Canvas.使用OnDrawPanel事件提供的StatusBar的Canvas:
procedure TForm1.StatusBar1DrawPanel(StatusBar: TStatusBar; Panel: TStatusPanel; const Rect: TRect); var RectForText: TRect; begin if (Panel = StatusBar.Panels[1]) and (Valid) then begin StatusBar.Canvas.Font.Color := clGreen; RectForText := Rect; StatusBar.Canvas.FillRect(RectForText); DrawText(StatusBar.Canvas.Handle, PChar(Panel.Text), -1, RectForText, DT_SINGLELINE or DT_VCENTER or DT_LEFT); end; end;
调用Repaint()或Invalidate()以强制状态栏重新绘制其绘图是要使用的方法.