Ir ao conteúdo
  • Cadastre-se

Pascal/Delphi Carregar Hint de um Form através de outro via Ini


Ir à solução Resolvido por Fazzioni,

Posts recomendados

Olá, estou tendo um pequeno problema no Delphi, estou tentando carregar um arquivo Ini, e jogar as configurações setadas nesse ini, nos objetos do form, nesse caso em especifico, os Hints.

Mas não importa como eu altere essa função, ele não altera os hints do do form, apesar que (na minha cabeça) não parece ter erro nesse código.

 


procedure TModulo.CarregarHints(Form: String);
var
  ArqIni: TIniFile;
  IForm: TForm;
  IComp: TComponent;
  x, CompMax: Integer;
  CompList: TStringList;
  xHint: String;
begin
  Form := PegarNomeForm(Form);
  ArqIni := TIniFile.Create(Config.Desconto_PathConfig+'Hints.ini');
  try
    if not ArqIni.SectionExists(Form) then
      Exit;
    IComp := Application.FindComponent(Form);
    if Assigned(IComp) then
      IForm := TForm(IComp)
    else
      Exit;
    CompList := TStringList.Create;
    ArqIni.ReadSection(Form, CompList);
    CompMax := CompList.Count-1;
    for x := 0 to CompMax do
    begin
      try
        IComp := IForm.FindComponent(CompList[x]);
        if Assigned(IComp) then
        begin
          xHint := Trim(StringReplace(ArqIni.ReadString(Form, CompList[x], ''), '#13', #13, [rfReplaceAll, rfIgnoreCase]));
          TForm(IComp).ShowHint := xHint <> EmptyStr;
          TForm(IComp).Hint := UTF8ToUnicodeString(xHint);
        end;
      except
        on E: Exception do
          ShowMessage(E.Message);
      end;
    end;
  finally
    IForm := nil;
    IComp := nil;
    if Assigned(CompList) then
      FreeAndNil(CompList);
    FreeAndNil(ArqIni);
  end;
end;

 

Com esse código, ele carregaria os hints, e jogaria em cada um dos componentes que estivessem escritos no ini.

 

Eu consegui fazer ele funcionar com o código:

 

Onde: THintsControl é um record com duas array's:

ArrayA: Array of Integer; //Guarda o Index do Componente

ArrayB: Array of String; //Guarda o Hint do Componente

 

function TModulo.CarregarHints(Form: String):THintsControl;
var
  ArqIni: TIniFile;
  IForm: TForm;
  IComp: TComponent;
  x, CompMax, CompIndex: Integer;
  CompList: TStringList;
  xHint: String;
begin
  Form := PegarNomeForm(Form);
  ArqIni := TIniFile.Create(Config.Desconto_PathConfig+'Hints.ini');
  try
    if not ArqIni.SectionExists(Form) then
      Exit;
    IComp := Application.FindComponent(Form);
    if Assigned(IComp) then
      IForm := TForm(IComp)
    else
      Exit;
    CompList := TStringList.Create;
    ArqIni.ReadSection(Form, CompList);
    CompMax := CompList.Count-1;
    SetLength(Result.ComponentsIndex, CompMax+1);
    SetLength(Result.ComponentsHints, CompMax+1);
    for x := 0 to CompMax do
    begin
      try
        IComp := IForm.FindComponent(CompList[x]);
        if Assigned(IComp) then
        begin
          CompIndex := IComp.ComponentIndex;
          xHint := StringReplace(ArqIni.ReadString(Form, CompList[x], ''), '#13', #13, [rfReplaceAll, rfIgnoreCase]);
          Result.ComponentsIndex[x] := CompIndex;
          Result.ComponentsHints[x] := UTF8ToUnicodeString(xHint);
        end
        else
        begin
          Result.ComponentsIndex[x] := -1;
          Result.ComponentsHints[x] := '';
        end;
      except
        on E: Exception do
          ShowMessage(E.Message);
      end;
    end;
  finally
    IForm := nil;
    IComp := nil;
    if Assigned(CompList) then
      FreeAndNil(CompList);
    FreeAndNil(ArqIni);
  end;
end;

 

 

E depois, no form que estou querendo carregar os hints, eu faço :

 

var
  x, xMax: integer;
begin
  HintsCtr := Modulo.CarregarHints(Self.Name);
  with HintsCtr do
  begin
    xMax := Length(ComponentsIndex)-1;
    for x := 0 to xMax do
    begin
      if ComponentsIndex[x] > -1 then
        TEdit(CadVeiculos.Components[ComponentsIndex[x]]).Hint := ComponentsHints[x];
    end;
  end;
end;

 

Mas parece ser uma gambiarra gigantesca fazer assim. Não teria um jeito correto de fazer o primeiro código funcionar? Onde apenas informando o nome do form, eu consigo carregar os hints corretamente?

Realmente agradeço a ajuda.

Link para o comentário
Compartilhar em outros sites

  • Solução

@jeffersoncg  aparentemente é um código válido, tente utilizar o breakpoint do delphi para verificar se a função está percorrendo a lista...

 

outra forma de fazer a mesma coisa:

procedure setHints(form:string);
var
  cfg : TIniFile;
  i : integer;
  comp : TComponent;
  s : string;
begin
 try
  comp := Application.FindComponent(form);
  if not Assigned(comp) then exit;

  cfg :=  TIniFile.Create(ExtractFilePath(Application.ExeName)+'Hints.ini');
  if not cfg.SectionExists(form) then
  exit;

    for i := 0 to comp.ComponentCount -1 do
    begin
      s := cfg.ReadString(comp.Name,comp.Components[i].Name,'');
      if (s <> '') and (comp.Components[i] is TControl) then
      with (comp.Components[i] as TControl) do
      begin
       Hint := s;
       ShowHint := true;
      end;
    end;
  finally
    FreeAndNil(cfg);
  end;
end;

 

  • Amei 1
Link para o comentário
Compartilhar em outros sites

16 minutos atrás, Fazzioni disse:

@jeffersoncg  aparentemente é um código válido, tente utilizar o breakpoint do delphi para verificar se a função está percorrendo a lista...

 

outra forma de fazer a mesma coisa:


procedure setHints(form:string);
var
  cfg : TIniFile;
  i : integer;
  comp : TComponent;
  s : string;
begin
 try
  comp := Application.FindComponent(form);
  if not Assigned(comp) then exit;

  cfg :=  TIniFile.Create(ExtractFilePath(Application.ExeName)+'Hints.ini');
  if not cfg.SectionExists(form) then
  exit;

    for i := 0 to comp.ComponentCount -1 do
    begin
      s := cfg.ReadString(comp.Name,comp.Components[i].Name,'');
      if (s <> '') and (comp.Components[i] is TControl) then
      with (comp.Components[i] as TControl) do
      begin
       Hint := s;
       ShowHint := true;
      end;
    end;
  finally
    FreeAndNil(cfg);
  end;
end;

 

 

Amigo era isso mesmo, eu não queria ter que rodar por todo o form e ele ler component por component, já que a lista era pré definida, ai no caso iria mais rápido.

O meu código lá de cima não pegava por causa do " as TControl".

 

Coloquei como você fez ai, e deu certo.

with (IComp as TControl) do
          begin
            ShowHint := xHint <> EmptyStr;
            Hint := UTF8ToUnicodeString(xHint);
          end;

 

Muito obrigado mesmo Fazzioni.

Link para o comentário
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisa ser um usuário para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...