Set variable Style on create / show form in Delphi XE2
-
31-05-2021 - |
質問
I'm trying to create a form with a user selected style saved to an ini file (JvFormStorage and JVIniFileStorage). The problem I have is if I put my code in the OnCreate it doesn't work, In the OnShow works but I get the error:
"Cannot change Visible in OnShow or OnHide"
even if this is the only code in the OnShow or in a procedure call (Green1 a MenuItem but will convert to combobox choices) I.e.:
Procedure TForm1.ChangeTheme;
begin
if Assigned(TStyleManager.ActiveStyle) then Begin
If (Green1.Checked) and (TStyleManager.ActiveStyle.Name<>'Light Green') then
TStyleManager.TrySetStyle('Light Green') else
... else
TStyleManager.TrySetStyle(fdefaultStyleName);
end;
Also tried:
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Form1.ChangeTheme;
Form1.Show;
Application.Run;
Does work but does flicker from normal windows to 'styled' and would prefer no flicker if possible.
I may well be going around this completely the wrong way. Thanks Paul
解決
In your case the OnCreate event is the proper place to load the vcl style.
This is a minimal sample working application, (the application must include the "carbon" and "auric" styles)
Project Code
program Project2;
uses
Vcl.Forms,
Unit1 in 'Unit1.pas' {Form1};
{$R *.res}
begin
Application.Initialize;
Application.MainFormOnTaskbar := True;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
Form Code
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Green1: TCheckBox;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses
Vcl.Styles,//including this unit init the vcl styles services.
Vcl.Themes;
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
fdefaultStyleName : string;
begin
fdefaultStyleName:='Auric';
if StyleServices.Enabled then
If (Green1.Checked) and (not SameText(TStyleManager.ActiveStyle.Name,'Carbon')) then
TStyleManager.TrySetStyle('Carbon')
else
TStyleManager.TrySetStyle(fdefaultStyleName);
end;
dfm
object Form1: TForm1
Left = 520
Top = 299
Caption = 'Form1'
ClientHeight = 294
ClientWidth = 534
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
OnCreate = FormCreate
PixelsPerInch = 96
TextHeight = 13
object Button1: TButton
Left = 32
Top = 256
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 0
end
object Green1: TCheckBox
Left = 32
Top = 56
Width = 97
Height = 17
Caption = 'Green1'
TabOrder = 1
end
end