Documentos Delphi
Documentos Delphi
com
Como?
161- Change the StringGrid's CELL color ?
160 - A listbox in a cell of a stringgrid
159 -- Pintar
158 umseBitmap
Verificar diretamente
a impressora no Canvas do Form
está ligada
157 - Obter a letra do drive onde está o Windows
156 - Mostrar o nome do EXE no caption do form
155 - Fazer pesquisa incremental apenas com DBGrid
154 - Obter tipo de uma propriedade
153 - Consulta SQL que usa a data do sistema
152 - Abrir uma conecção Dial-Up
151 - Pintar uma imagem JPG no form
150 - Executar comando do MS-DOS
149 - Formatar CEP
148 - Permitir cancelar processo demorado
147 - Descobrir se uma data é fim do mês
146
145 - Programar
Obter o tipoteclas de atalho
de dado de um do Windows
valor no Registro do Windows
144 - Obter a célula de um StringGrid que está sob o cursor do mouse
143 - Limpar todas as células de um StringGrid
142 - Programar meu aplicativo para abrir arquivos a partir do Windows Explorer
141 - Consultar por mês de um campo data
140 - Criando tabelas via SQL
139 - Obter nomes dos campos de uma tabela
138 - Nomeando um relatório no spool de impressão do Windows
137 - Obter tamanho de um arquivo
136 - Ocultar aplicação da lista de tarefas - CTRL+ALT+DEL
135 - Obter path de um Alias do BDE
134 - Ativar a proteção de tela do Windows
133 - Abrir
132 Desligar/Ligar
e fechar omonitor
drive de CD-ROM
131 - Impedir que o form seja arrastado para fora das margens da tela
130 - Mostrar mensagem mesmo que esteja no Prompt do DOS
129 - Copiar todos os registros de uma tabela para o Clipboard
128 - Copiar um registro de uma tabela para o Clipboard
127 - Criar sub-diretório no diretório do EXE
126 - Ocultar o aplicativo do CTRL+ALT+DEL
125 - Personalizar a caixa de mensagem de exceções (erro) do Delphi
124 - Implementar procedure Delay do Pascal no Delphi
123 - Enviar comandos de rolagem vertical para um TMemo
122 - Criar uma DLL de Bitmaps e usá-la
121 - Construir a barra de título do form com um Panel
120 - Criar form sem título que possa ser arrastado
119 - Obter status da memória do sistema
118 - Definir data/hora de um arquivo
117 - Mostrar o diálogo About (Sobre) do Windows
116 - Ocultar/exibir o cursor do mouse
115 - Converter de Hexadecimal para Inteiro
114 - Mudar a cor de um DBEdit dentro de um DBCtrlGrid de acordo com uma condição
113 - Colocar uma ProgressBar da StatusBar
112 - Executar um programa e aguardar sua finalização antes de continuar
111 - Simular o pressionamento de uma combinação de teclas (ex: Ctrl+F2)
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 1/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 2/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 3/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
private
Bmp: TBitmap;
- Coloque um botão no Form e no evento OnClick digite:
Bmp:= TBitMap.Create;
try
Bmp.LoadFromFile('c:\teste\arquivo.bmp');
Canvas.Draw(0,0, Bmp);
finally
Bmp.Free;
end;
Problema:
Faço impressão direta para a porta da impressora e gostaria
testar se aIsto
relatório. impressora
é possívelestá
em pronta
Delphi?antes de enviar o
Solução:
Usando instruções Assembly podemos fazer isto. A função
abaixo retorna true se a porta informada está pronta.
Os possíveis parâmetros para esta função são:
1 - para LPT1
2 - para LPT2
3 - para LPT3
4 - para LPT4
function tbTestLPT(Port: byte): boolean;
var
Pto : Word;
Rdo : byte;
begin
Pto := Port -1;
asm
MOV DX,Pto
MOV AX,$0200 {AH := $02 : Leer el estado de la impresora}
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 4/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
INT $17
MOV Rdo,AH {Guarda el estado en AL}
end;
Result := Rdo = 144;
end;
Observações
Provavelmente esta função não funcionará em Windows NT devido ao acesso em baixo nível.
Problema:
Como saber em qual unidade de disco (drive) o Windows está
instalado?
Solução:
Esta função retorna a letra do drive onde está instalado o
Windows:
function GetWindowsDrive: Char;
var
S: string;
begin
SetLength(S, MAX_PATH);
if GetWindowsDirectory(PChar(S), MAX_PATH) > 0 then
Result := string(S)[1]
else
Result := #0;
end;
{ Exemplo de uso: }
procedure TForm1.Button1Click(Sender: TObject);
begin
Caption := GetWindowsDrive;
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 5/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
{ Coloca a primeira letra em maiúscula e o resto
em minúscula }
Titulo := UpperCase(Copy(D,1,1)) +
LowerCase(Copy(D,2,Length(D)-1));
end;
{ No OnCreate do form, coloque: }
procedure TForm1.FormCreate(Sender: TObject);
begin
Caption := Titulo(ParamStr(0));
end;
- Dica enviada por: Luiz Eduardo.
Problema:
Gostaria de fazer um formulário de pesquisa que, ao digitar
algo sobre o DBGrid, o registro correspondendo fosse
localizado.
Solução:
- Coloque no form: TTable, TDataSource, TDBGrid e TLabel.
- Ajuste as propriedades do Table1:
DatabaseName =
TableName =
Active = true
- Ajuste as propriedades do DataSource1:
DataSet = Table1
- Ajuste as propriedades do DBGrid1:
DataSource = DataSource1
Options -> dgEditing = false
ReadOnly = true
* Pode também ajustar a propriedades Columns para escolher
as colunas que serão exibidas.
- Na seção private da unit declare:
private
FTexto: string;
- No evento OnCreate do form coloque:
FTexto := '';
Label1.Caption := '';
- No evento OnKeyPress do DBGrid1:
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 6/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 7/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Problema:
Preciso fazer uma consulta com SQL que me retorne todos
os registros em que o valor de um campo do tipo data seja
igual ou anterior à dada do sistema. Como fazer?
Solução:
Query.Close;
Query.SQL.Text := 'select * from Tabela where CampoData <= :Hoje';
Query.ParamByName('Hoje').AsDate := Date;
Query.Open;
Observações
Este exemplo foi testado com tabelas Paradox, mas deve funcionar na maioria dos bancos
de dados com pouca ou nenhuma alteração.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 8/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Usando
Para istoWinExec
chame ovocê pode executar
COMMAND.COM qualquercomo
passando comando do DOS.
parâmetro a linha
de comando a ser executada. O parâmetro /C é opcional e faz
com que a janela do DOS seja fechada assim que o comando
terminar. No exemplo abaixo estou executando a seguinte
linha de comando: DIR C:\*.*
WinExec('COMMAND.COM /C DIR C:\*.*', SW_SHOW);
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 9/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Observações
Para que a janela do DOS não seja exibida, use SW_HIDE no lugar de SW_SHOW.
Observações
Para formatar outros códigos como CPF, CGC, etc., pode-se usar a mesma idéia.
Problema:
Em determinadas partes no programa existem processos que podem
demorar vários minutos para serem concluídos. Muitas vezes o
usuário desiste e deseja cancelar o processamento. Como
permitir este cancelamento?
Solução:
Em aplicativos para Windows é comum, em processamentos
demorados, o programa mostrar uma janela de diálogo avisando
que o processo pode levar um tempo extra. Nesta mesma janela
normalmente coloca-se também um botão "Cancelar" que dá ao
usuário a opção aguardar ou desistir do processo. Para fazer
isto em um aplicativo Delphi, siga os passos abaixo:
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 10/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
public;
Cancelar: boolean;
- Crie um novo form (vou chamá-lo de Form2);
- Coloque um botão neste novo form. Programe o OnClick deste
botão conforme abaixo:
Form1.Cancelar := true;
- Na parte onde ocorre o loop do processamento demorado
coloque algo como:
try
{ Antes de começar
Form2.Caption o processamento
:= 'Processamento }
demorado...';
Form2.Show;
{ No início do loop "Cancelar" precisa ser false }
Cancelar := false;
{ Aqui inicia o loop do processamento demorado }
while {...} do begin
{ ... Processa algo aqui... }
{ Permite que o programa processe mensagens do Windows }
Application.ProcessMessages;
{ Se a variável "Cancelar" foi alterada para true... }
if Cancelar then begin
ShowMessage('Operação cancelada pelo usuário.');
Break; { Sai do loop }
end;
end;
finally
Form2.Close;
end;
Observações
Não se esqueça de que o Form1 precisa usar Form2 e vice-versa.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 11/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 12/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
end;
- Execute este programa e experimente pressionar Ctrl+Alt+F11
ou Ctrl+Alt+F12.
Observações
Se a combinação
usá-la de teclas já
em nossa aplicação. estiveroutras
Existem em uso (num de
formas atalho, por exemplo),
implementar teclasnão será possível
de atalho em
programas escritos em Delphi, mas a forma apresentada é bastante funcional.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 13/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 14/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 15/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Solução:
Para fazer
Registro doisto será necessária
Windows. O exemploa criação de algumas
abaixo cria todas aschaves
chavesno
necessárias.
{ *.dpg }
Reg.OpenKey('.dpg', true);
Reg.WriteString('', 'ArquivoDaniel');
Reg.CloseKey;
{ *.dan }
Reg.OpenKey('.dan', true);
Reg.WriteString('', 'ArquivoDaniel');
Reg.CloseKey;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 16/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
finally
Reg.Free;
end;
end;
- Coloque um TMemo;
- No evento OnShow do Form coloque o código abaixo:
procedure TForm1.FormShow(Sender: TObject);
begin
{ Se o primeiro parâmetro for um nome de arquivo existente... }
if FileExists(ParamStr(1)) then
{ Carrega o conteúdo do arquivo no memo }
Memo1.Lines.LoadFromFile(ParamStr(1));
end;
Problema:
Tenho um cadastro de clientes com Codigo, Nome, DataNasc, etc.
Preciso fazer uma consulta onde apareceão apenas os clientes
que fazem aniversário em determinado mês. Como fazer?
Solução:
Use uma Query como abaixo:
- Coloque no form os seguintes componentes:
* TQuery
* TDataSource
* TDBGrid
TEdit
* TButton
- Altere as propriedades dos componentes como abaixo:
* Query1.DatabaseName = (alias do BDE)
* DataSource1.DataSet = Query1
* DBGrid1.DataSource = DataSource1
- Coloque o código abaixo no evento OnClick de Button1:
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 17/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Query1.Close;
Query1.SQL.Clear;
Query1.SQL.Add('select * from dCli');
Query1.SQL.Add('where extract(month from DataNasc) = :Mes');
Query1.ParamByName('Mes').AsInteger := StrToInt(Edit1.Text);
Query1.Open;
- Execute. Digite um número de 1 a 12 no Edit e clique no
botão.
Observações
Os números de 1 a 12 representam, respectivamente, os meses de Janeiro a Dezembro. Este
exemplo foi testado com Delphi4, BDE5 e tabela Paradox7.
Este exemplo
outros bancosfoi
detestado compouca
dados com bancoou
denenhuma
dados Paradox, porém
alteração. deverá funcionar em vários
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 18/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Problema:
Quando mandamos imprimir no Windows, normalmente o nome do
documento aparece na fila de impressão (spool). Como fazer
com que aplicativos feitos em Delphi se comporte desta
forma? Ou seja, como nomear meus relatórios feitos em Delphi?
Solução:
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 19/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 20/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 21/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 22/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Problema:
Fiz um programa que mostra mensagens de lembrete quando é
chegada determinada data/hora. Porém quando o usuário vai
para o Prompt do MS-DOS em modo tela cheia, a mensagem
não aparece. O que devo fazer?
Solução:
Antes de mostrar a mensagem, coloque sua aplicação na frente
das demais.
SetForegroundWindow(Application.Handle);
ShowMessage('Teste');
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 23/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
end;
Clipboard.AsText := S;
end;
Para testar:
- Execute este aplicativo;
Clique
- Vá no botão;
em outro aplicativo (ex: MS-Word) e mande colar (Ctrl+V).
Observações
CUIDADO! Não use este recurso com tabelas grandes, pois poderá usar memória
demasiadamente. No teste que fiz, o tamanho da string S atingiu 20K e funcionou
normalmente. Mas isto pode variar de uma máquina para outra.
Problema:
Gostaria de colocar em minha aplicação o recurso de copiar
um registro de uma tabela para a área de transferência,
permitindo ao usuário colar estes dados em outro
aplicativo (ex: MS-Word). Isto é possível?
Solução:
Sim. Siga os passos abaixo:
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 24/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Problema:
Gostaria de criar um sub-diretório dentro do diretório
onde se encontra o EXE de minha aplicação. Como fazer?
Solução:
Primeiramente vamos conhecer algumas funções do Delphi
que precisaremos usá-las:
ParamStr(Indice) - Retorna valores passados
na linha de comando quando executamos o programa. Se o valor
de Indice for 0 (zero) será retornado o caminho+nome do EXE.
ExtractFilePath(NomeArq) - Retorna o caminho (path) do
nome de arquivo informado.
Exemplo:
S := 'C:\NomeDir\Programa.exe';
ExtractFilePath(S); { retorna: 'C:\NomeDir\' }
DirectoryExists(CaminhoDir) - Retorna true se o diretório
informado existe. False em caso contrário.
CreateDir(CaminhoDir) - Tenta criar o diretório informado.
Se conseguir, retorna true. Caso contrário retorna false.
Agora queuma
escrever sabemos
funçãocomo trabalham estas
que precisamos funções,
para criar um vamos
sub-diretório conforme proposto.
function CriaSubDir(const NomeSubDir: string): boolean;
var
Caminho: string;
begin
Caminho := ExtractFilePath(ParamStr(0)) + NomeSubDir;
if DirectoryExists(Caminho) then
Result := true
else
Result := CreateDir(Caminho);
end;
Exemplo de uso:
- Chame a função no evento OnCreate do form:
procedure TForm1.FormCreate(Sender: TObject);
begin
if not CriaSubDir('MeuSubDir') then
ShowMessage('Não foi possível criar o sub-diretório MeuSubDir.');
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 25/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
end;
Problema:
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 26/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
begin
MessageDlg(E.Message + #13#13 +
'Suporte técnico:'#13 +
'[email protected]',
mtError, [mbOK], 0);
end;
- No evento OnCreate do Form principal escreva o código
abaixo:
procedure
var Delay(MSec: Cardinal);
Start: Cardinal;
begin
Start := GetTickCount;
repeat
Application.ProcessMessages;
until (GetTickCount - Start) >= MSec;
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 27/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Solução:
Sim. Utilizando mensagens do Windows isto é fácil. Vejamos
algums exemplos:
SendMessage(Memo1.Handle, WM_VSCROLL, SBPAGEDOWN, 0);
Onde:
Memo1.Handle = manipulador da janela do Memo1.
WM_VSCROLL = Mensagem do Windows - rolagem vertical.
SB_PAGEDOWN = Comanndo de rolagem - página para baixo.
Outros exemplos:
Problema:
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 28/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Solução:
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 29/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
end;
end;
Pegue o arquivo
do IntereSite: tbtitle.zip na seção Download
www.ulbrajp.com.br/~tecnobyte
Problema:
Fazer um relógio num form é fácil. Porém gostaria que esse
form não possuísse a barra de título, mas que o usuário
ainda pudesse arrastá-lo com o mouse. Isto é possível
no Delphi?
Solução:
Sim, é possível e é fácil. Siga os passos abaixo:
- Crie um novo projeto;
- Mude as seguintes propriedades do Form1:
BorderStyle = bsNone, FormStyle = fsStayOnTop,
- Coloque um Label;
- Coloque um Timer;
- Altere o evento OnTimer do Timer1 conforme abaixo:
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Label1.Caption := TimeToStr(Time);
end;
- Altere o evento OnCreate do Form1 conforme abaixo:
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 30/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Label1.Left := 10;
Label1.Top := 10;
end;
private
procedure WMNCHitTest(var Msg: TMessage);
message WM_NCHitTest;
public
{ Public declarations }
end;
- Vá na seção implementation e escreva a procedure abaixo:
implementation
{$R *.DFM}
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 31/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
[M.dwTotalPhys / cBytesPorMb]));
Add(Format('Memória física disponível: %f MB',
[M.dwAvailPhys / cBytesPorMb]));
Add(Format('Tamanho máximo do arquivo de paginação: %f MB',
[M.dwTotalPageFile / cBytesPorMb]));
Add(Format('Disponível no arquivo de paginação: %f MB',
[M.dwAvailPageFile
Add(Format('Total de /memória
cBytesPorMb]));
virtual: %f MB',
[M.dwTotalVirtual / cBytesPorMb]));
Add(Format('Memória virtual disponível: %f MB',
[M.dwAvailVirtual / cBytesPorMb]));
end;
end;
{sucesso
Esta função altera
retorna a data
true, casoecontrário
hora de um arquivo.
retorna false.Se} obter
function DefineDataHoraArq(NomeArq: string; DataHora: TDateTime): boolean;
var
F: integer;
begin
Result := false;
F := FileOpen(NomeArq, fmOpenWrite or fmShareDenyNone);
try
if F > 0 then
Result := FileSetDate(F, DateTimeToFileDate(DataHora)) = 0;
finally
FileClose(F);
end;
end;
{ Exemplo de uso 1: Usa a data atual do sistema (Now) }
if DefineDataHoraArq('c:\teste\logo.bmp', Now) then
ShowMessage('Data/Hora do arquivo definida com sucesso.')
else
ShowMessage('Não foi possível definir data/hora do arquivo.');
{ Exemplo de uso 2: Usa uma data fixa }
var
DataHora: TDateTime;
begin
{ Define a data para 5-Fev-1999 e a hora para 10:30 }
DataHora := EncodeDate(1999, 2, 5) + EncodeTime(10, 30, 0, 0);
if DefineDataHoraArq('c:\teste\logo.bmp', DataHora) then
ShowMessage('Data/Hora do arquivo definida com sucesso.')
else
ShowMessage('Não foi possível definir data/hora do arquivo.');
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 32/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
procedure
begin TForm1.Button1Click(Sender: TObject);
ShellAbout(Handle, 'Sistema Financeiro', 'Marcelo Senger',
Application.Icon.Handle);
end;
Observações
Dica enviada por: Marcelo Senger
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 33/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Problema:
Uso um DBCtrlGrid e gostaria que, quando o valor de um
determinado campo for negativo, o DBEdit ligado a este
campo seja exibido em vermelho e, caso contrário,
em azul. Isto é possível?
Solução:
- Monte o form normalmente colocando DataSource, Table,
DBCtrlGrid e os DBEdit's, DBText's, etc.
- Escreva no manipulador do evento OnPaintPanel do
DBCtrlGrid conforme abaixo:
procedure TForm1.DBCtrlGrid1PaintPanel(DBCtrlGrid: TDBCtrlGrid;
Index: Integer);
begin
if Table.FieldByName('NomeDoCampo').AsFloat < 0 then
DBEdit1.Font.Color := clRed
else
DBEdit1.Font.Color := clBlue;
end;
Observações
Neste exemplo mudamos a cor da fonte do componente DBEdit, Porém, pode-se também
mudar a cor do próprio componente (DBEdit1.Color).
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 34/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Coloque
- Digite noum Button
evento no form
OnClick do Button o código abaixo:
procedure TForm1.Button1Click(Sender: TObject);
var
I: integer;
begin
for I := ProgressBar1.Min to ProgressBar1.Max do begin
{ Atualiza a posição da ProgressBar }
ProgressBar1.Position := I;
{ Repinta a StatusBar para forçar a atualização visual }
StatusBar1.Repaint;
{ Aguarda 50 milisegundos }
Sleep(50);
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 35/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
end;
- Execute e clique no botão para ver o resultado.
Observações
Com um pouco de criatividade podemos fazer outras coisas interessantes usando o evento
OnDrawPanel da StatusBar.
- Exemplo de uso:
ExecAndWait('c:\windows\notepad.exe', '', SW_SHOW);
Observações
Não se esqueça de informar o caminho (path) do arquivo completo. Esta função foi
desenvolvida para Delphi 32 bits (2, 3, 4,...).
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 36/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 37/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 38/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
{ligada.
Esta função
False retorna
em casotrue se a tecla
contrário } informada estiver
function tbKeyIsOn(const Key: integer): boolean;
begin
Result := GetKeyState(Key) and 1 > 0;
end;
{ Exemplo de uso: }
if tbKeyIsOn(VK_NUMLOCK) then
{ ... NumLock está ligada }
else
{ ... NumLock está desligada }
Observações
Qualquer tecla que possua os estados On/Off pode ser verificada. Basta, para isto, saber seu
código. O código de CapsLock é VK_CAPITAL.
procedure
begin TForm1.FormCreate(Sender: TObject);
StringGrid1.RowHeights[0] := 15;
StringGrid1.RowHeights[1] := 20;
StringGrid1.RowHeights[2] := 50;
StringGrid1.RowHeights[3] := 35;
end;
Observações
Cuidado para não especificar uma linha inexistente.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 39/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Solução:
É possível sim. Afinal é muito simples. Siga os passos abaixo
para resolver seu problema:
{$R *.DFM}
procedure TForm1.DBGridClick(Sender: TObject);
begin
ShowMessage('Clicou no DBGrid.');
end;
- Coloque as instruções abaixo no evento OnCreate do Form:
procedure TForm1.FormCreate(Sender: TObject);
begin
DBGrid1.ControlStyle :=
DBGrid1.ControlStyle + [csClickEvents];
TForm(DBGrid1).OnClick := DBGridClick;
end;
- E pronto. Execute e teste.
Observações
O segredo principal desta dica está OnCreate do Form. A primeira instrução ativa o evento
OnClick. A segunda instrução acessa o manipulador do evento OnClick. Para isto precisamos
tratar o DBGrid como se fosse Form, pois o evento OnClick está declarado como protegido
(protected) na classe TDBGrid.
A função
que podeabaixo demonstra
ser usada a criação
para permitir de umadigitar
ao usuário caixa de diálogo
o seu
nome:
{ Esta função retorna true se for pressionado OK e false
em caso contrário. Se for OK, o texto digitado pelo usuário
será copiado para a variável Nome }
function ObterNome(var Nome: string): boolean;
var
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 40/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 41/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
with Edit2 do
if Text <> '' then
Text := AnsiUpperCase(Text[1]) + Copy(Text, 2, Length(Text));
Isto pode ser colocado, por exemplo, no OnExit do Edit.
Você pode também converter durante a digitação. Para isto
coloque o código abaixo no evento OnKeyPress do Edit:
if Edit1.SelStart = 0 then
Key := AnsiUpperCase(Key)[1]
else
Key := AnsiLowerCase(Key)[1];
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 42/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Problema:
Um processamento em meu sistema é bastante demorado e por isto
colocar apenas o cursor de ampulheta continua deixando o
usuário confuso, pensando que o sistema travou. É possível
exibir uma mensagem enquanto um processamento demorado ocorre?
Sim. E é fácil. Vejamos:
- Crie um form com a mensagem. Um pequeno form com um
Label já é suficiente. Aqui vou chamá-lo de FormMsg.
- Vá em Project|Options e passe o FormMsg de
"Auto-create forms" para "Available forms".
- Abaixo vou simular um processamento demorado, usando a
API Sleep:
procedure TForm1.Button1Click(Sender: TObject);
var
Form: TFormMsg;
I: integer;
begin
Form := TFormMsg.Create(Self);
try
Form.Label1.Caption := 'Processamento demorado...';
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 43/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Form.Show;
for I := 1 to 5 do begin
Form.UpDate;
Sleep(1000); { Aguarda um segundo }
end;
finally
Form.Free;
end;
end;
Observações
A função Sleep é uma API do Windows e serve para paralisar a aplicação por um
determinado dempo. Este tempo é em milisegundos.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 44/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
type
{ Declara um tipo registro }
TFicha = record
Codigo: integer;
Nome: string[40];
DataCadastro: TDateTime;
end;
- Escreva o evento OnClick do Button1 conforme abaixo:
procedure TForm1.Button1Click(Sender: TObject);
var
Reg: TRegistry;
Ficha: TFicha;
begin
{ Coloca alguns dados na variável Ficha }
Ficha.Codigo := StrToInt(Edit1.Text);
Ficha.Nome := Edit2.Text;
Ficha.DataCadastro := StrToDate(Edit3.Text);
Reg := TRegistry.Create;
try
{ Define a chave-raiz do registro }
Reg.RootKey := HKEY_CURRENT_USER;
{ Abre uma chave (path). Se não existir cria e abre. }
Reg.OpenKey('Cadastro\Pessoas\', true);
{ Grava os dados (o registro) }
Reg.WriteBinaryData('Dados', Ficha, SizeOf(Ficha));
finally
Reg.Free;
end;
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 45/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
if Reg.ValueExists('Dados') then
begin
{ Lê os dados }
Reg.ReadBinaryData('Dados', Ficha, SizeOf(Ficha));
Edit1.Text := IntToStr(Ficha.Codigo);
Edit2.Text := Ficha.Nome;
Edit3.Text
end else := DateToStr(Ficha.DataCadastro);
ShowMessage('Valor não existe no registro.')
end else
ShowMessage('Chave (path) não existe no registro.');
finally
Reg.Free;
end;
end;
Observações
Qualquer tipo de dado pode ser gravado e lido de forma binária no registro do Windows.
Para isto você precisa saber o tamanho do dado. Para dados de tamanho fixo, use SizeOf().
Lembrete:
prejudicaránão grave dadosdo
o desempenho muito extensos
sistema. no Registro do Windows (ex: imagens), pois isto
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 46/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Observações
Nos testes que fiz, nem tudo funcionou adequadamente. Mas vale a pena experimentar.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 47/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 48/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Key := AnsiLowerCase(Key)[1];
Problema:
Gostaria de montar um formulário de pesquisa com um DBGrid e
um Edit de modo que, enquanto o usuário digita um nome do
Edit, o registro vai sendo localizado no DBGrid. Como fazer?
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 49/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
- DataSource1.DataSet = Table1
- Table1.DatabaseName = 'NomeDoAlias'
- Table1.TableName = 'NomeDaTabela'
- Table1.IndexFieldNames = 'NomeDoCampo'
- Table1.Active = true
- DBGrid1.DataSource = DataSource1
Escreva a instrução abaixo no evento OnChange do Edit:
Table1.FindNearest([Edit1.Text]);
Observações
Este exemplo considera que o campo seja tipo string. Para outros tipos de campos pode
ocorrer erro dependendo dos valores digitados no Edit1.
while Length(Result)
Result < Casas do
:= Ch + Result;
end;
{ Exemplo de como usá-la: }
var
S: string;
Numero: integer;
{...}
begin
{...}
S := tbStrZero(Numero, 6);
{...}
end;
Observações
Se o comprimento desejado (Casas) não for suficiente para conter o número, serão
colocados asteriscos.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 50/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Table1.FieldByName('Data').Clear;
{ ou }
Table1.FieldByName('Data').AsString := '';
Observações
Podemos usar este recurso para limpar também campos numéricos, string, etc.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 51/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
procedure
var TForm1.Button1Click(Sender: TObject);
pw: TPasswordDialog;
begin
pw := TPasswordDialog.Create(Self);
try
pw.Caption := 'Banco de Dados';
pw.GroupBox1.Caption := 'Senha';
pw.AddButton.Caption := '&Adicionar';
pw.RemoveButton.Caption := '&Remover';
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 52/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 53/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 54/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
end;
{ Use-a como abaixo: }
var
Lin, Col: Cardinal;
begin
tbGetMemoLinCol(Memo1, Lin, Col);
{ ... }
end;
{ === SOLUÇÃO 2 === }
var
Lin, Col: integer;
begin
Lin := Memo1.CaretPos.y;
Col := Memo1.CaretPos.x;
{...}
end;
- A segunda solução foi apresentada por:
Vanderley Pereira Rocha
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 55/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
function tbGetEnvVar(const VarName: string): string;
var
I: integer;
begin
Result := '';
{ Obtém o comprimento da variável }
I := GetEnvironmentVariable('PATH', nil, 0);
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 56/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
{ Solução 2: }
var
Pt: TPoint;
begin
GetCursorPos(Pt);
if WindowFromPoint(Pt) = Button1.Handle then
{ Está no botão }
else
{ Não está no botão }
end;
Observações
A API GetWindowRect obtém o retângulo (TRect) ocupado por uma janela. Podemos usar
GetClientRect para obter o somente da parte cliente da janela. Podemos também usar a
propriedade BoundsRect que existe na maioria dos componentes visuais, ou mesmo
informar qualquer outro retângulo da tela. Se usarmos a propriedade BoundsRect,
precisaremos converter as coordenadas clientes para coordenadas de tela (com a função
ClientToScreen). Um lembrete: a solução 2 só poderá ser aplicada a controles ajanelados.
Observações
Pode-se verificar qualquer janela (form). Só um lembrete: quando clicamos no botão de
minimizar do form principal, na verdade ele é oculto e o Application é que é minizado.
Observações
A função FatalAppExit é uma API do Windows. Esta mostra uma caixa de diálogo
(normalmente branca) com a mensagem passada no segundo parâmetro. Quando a caixa de
diálogo é fechada a aplicação é finalizada. O evento OnCloseQuery dos forms não são
chamados quando usamos esta função.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 57/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
{ Problema:
Tenho um sistema de contas a receber, onde um campo chamado
"Tipo" contém um número inteiro que indica o tipo do
documento conforme abaixo:
1 - Promissória
2 - Duplicata
3 - Boleto
Gostaria que, ao exibir os dados (num DBGrid por exemplo),
fosse exibido o nome e não o número, ou seja, "Promissória"
em vez de "1".
Solução:
Isto pode ser feito de várias formas, mas aqui vou mostrar
como resolver usando o evento OnGetText do TField. Vejamos:
- Adicione todos os campos no Field Editor;
- Clique no campo "Tipo";
- Vá ao Object Inspector e dê um duplo-click
no evento OnGetText;
- Neste evento, digite o código abaixo:
}
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 58/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 59/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
{ Problema:
Gostaria que um determinado programa (Prog1.EXE) fosse
executado apenas através de outro programa (Prog2.EXE).
Solução:
Antes da linha "Application.Initialize;" de Prog1.dpr (programa
a ser chamado), coloque o código abaixo:
}
if ParamStr(1) <> 'MinhaSenha' then begin
{ Para usar ShowMessage, coloque Dialogs no uses }
ShowMessage('Execute este programa através de Prog2.EXE');
Halt; { Finaliza }
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 60/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Look:
Problema:
Estou com um problemão. Trabalho com o NT 4 workstation
Service Pack 3, Delphi 3 e Interbase 4.2.xxx. E instalei o
Interbase 5.1.1 Server nesta máquina. Até aí tudo bem. Quando
fui rodar
tipo a aplicação
de Dado. deram
Analisando alguns problemas
o problema de conversão
percebi que havia do
esquecido de instalar o Client do Interbase. Foi aí que
começaram os problemas. Tentei instalar o client, porém o
instalador após preparar os arquivos de instalação mostrava
a seguinte mensagem e parava : Titulo da janela = "Severe",
mensagem = "Internal error near: IBCheck"; comecei a ler os
manuais, em certo ponto aconselhava desinstalar qualquer
versão posterior do Interbase da minha máquina. Foi então que
desinstalei o Interbase 4.2.xxx (através do "Control Panel",
"Add/Remove Programs"). Nova tentativa de instalar o client,
o erro persistia. Resolvi desinstalar (através do "Control
Panel", "Add/Remove Programs") todo o Interbase da minha
máquina e começar
novamente tudo
o Interbase de novo.
Server, Porém oquando
surpresa, tentei instalar
erro apareceu
novamente. Mas agora não havia interbase instalado. Fui
desinstalando Delphi, BDE, ... e nada. Entrei no Regedit,
pois o desinstalador, normalmente, faz o trabalho incompleto
e é necessário excluir um monte de lixo do Registry.
Deparei com a seguintes chaves:
hkey_local_machine\system\controlset001\enum\root\legacy_interbase_guard
hkey_local_machine\system\controlset001\enum\root\legacy_interbase
Tentei excluí-las, porém são chaves protegidas, e o regedit
não permitiu que eu excluísse-as.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 61/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
HKEY_CURRENT_USER\Environment
Renata Oliva
Inprise Support Center
{ Define }
SetDoubleClickTime(300);
end;
Observações
Um duplo-click nada mais é que dois cliques consecutivos (óbvio). Porém estes dois cliques
podem ser interpretados de duas formas: dois cliques isolados ou um duplo-click. Para o
Windows resolver esta situação, ele usa o que chamo de "tempo máximo do duplo-click". Se
o intervalo entre o primeiro e o segundo click for menor ou igual a esse tempo, então houve
duplo-click. E você pode alterar este tempo. O padrão do Windows é 500 milisegundos. Um
tempo muito curto (ex: 100), faz com que o duplo-click tenha que ser muito rápido (quase
impossível), enquanto muito longo (ex: 2000) faz com que o Windows interprete dois clicks
isolados como duplo-click.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 62/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
- Coloque um edit;
- Coloque um botão e escreva seu OnClick como abaixo: }
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 63/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
{Agrupamentos.
O exemplo acimaSe retorna
preferir as medidas
algo em Bytes, Setores e
mais simples,
use funções do Delphi. Veja: }
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 64/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Observações
Para testar digite a letra do drive no Edit1 e clique no botão. A unit Dialogs foi colocada no
uses apenas por causa da procedure ShowMessage. Para exibir todas as unidades existentes
e seus respectivos tipos, use a função tbGetDrives (da pergunta 64) em conjunto com este
exemplo.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 65/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 66/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Observações
Isto pode não funcionar se ValorReal for muito alto. Isto por causa da multiplicação que
poderá estourar a capacidade do tipo em uso. Lembre-se: os tipos reais aceitam valores
muuuiiiito altos.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 67/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 68/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
cFExpandido = #20;
{ Formatação da fonte }
cINegrito = #27#71;
cFNegrito = #27#72;
cIItalico = #27#52;
cFItalico = #27#53;
var
Texto: string;
F: TextFile;
begin
Texto := c10cpi +
'Este e um teste para impressora Epson LX 300. ' +
'O objetivo e imprimir texto justificado sem deixar ' +
'de usar formatacao, tais como: ' +
cINegrito + 'Negrito, ' + cFNegrito +
cIItalico + 'Italico, ' + cFItalico +
c17cpi + 'Condensado (17cpi), ' + c10cpi +
c12cpi + '12 cpi, ' + c10cpi +
cIExpandido + 'Expandido.' + cFExpandido +
' Este
'a sua erealidade
apenas um exemplo,
conforme mas voce podera adapta-lo ' +
a necessidade.';
AssignFile(F, 'LPT1');
Rewrite(F);
try
WriteLn(F, cJustif, Texto);
WriteLn(F, cEject);
finally
CloseFile(F);
end;
end;
Observações
Este recurso de justificação da Epson LX-300 pode ser usado em qualquer linguagem de
programação.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 69/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 70/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 71/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
como abaixo: }
procedure TForm1.Button1Click(Sender: TObject);
var
Reg: TRegIniFile;
S: string;
begin
Reg := TRegIniFile.Create('SOFTWARE\MICROSOFT\MS SETUP (ACME)\');
try
S := Reg.ReadString('USER INFO','DefName','');
S := S + #13;
S := S + Reg.ReadString('USER INFO','DefCompany','');
ShowMessage(S);
finally
Reg.free;
end;
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 72/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 73/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Observações
Ao executar observe a barra de tarefas e teste o Alt+Tab (seu programa não estará lá!).
{ Evento Pergunta }
MessageBeep(32);
{ Evento Exclamação }
MessageBeep(48);
{ Evento Asterisco }
MessageBeep(64);
{ Reinicia o Windows }
ExitWindowsEx(EWX_REBOOT, 0);
{ Desliga o Windows }
ExitWindowsEx(EWX_SHUTDOWN, 0);
{ Força todos os programa a desligarem-se }
ExitWindowsEx(EWX_FORCE, 0);
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 74/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 75/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Table1.RecNo()
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 76/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 77/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Display := Form2;
Form2.Show;
Play;
end;
end;
Observações
Em vez de ajustar o Form ao vídeo, podemos ajustar o vídeo ao Form. Para isto troque o
trecho with..end; por MediaPlayer1.DisplayRect := Form2.ClientRect;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 78/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Observações
"S" precisa ser uma variável string.
35 - Copiar arquivos
{--Altere
Coloque um Button
o evento no Form;
OnClick deste Button conforme abaixo: }
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 79/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 80/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Observações
Há uma margem de erro nesta verificação: pode haver outros programas que possuam uma
janela com os mesmos nomes. Você mesmo pode criar aplicativos em Delphi e,
propositadamente, criar uma janela com um destes nomes. Veja a pergunta nº 18.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 81/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 82/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
var
Total: integer;
begin
Check(DbiGetRecordCount(Table1.Handle, Total));
ShowMessage('Total de registros: ' + IntToStr(Total));
end;
Observações
Para testar o exemplo acima, o Table1 precisa estar aberto.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 83/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Observações
Para testar este programa você deverá compilar o projeto e fechar o Delphi. Depois, procure
o Project1.exe (projeto compilado) usando o Windows Explorer e tente executá-lo mais de
uma vez e veja o que acontece. Mas porque alterar o name do form principal para
"DPGFormPrinc"? Este poderia ser qualquer outro nome, mas preferi usar as iniciais do meu
nome (DPG). Procurei deixar um nome bem pessoal para não correr o risco de colocar um
nome que possa ser encontrado em outro aplicativo do Windows. Por exemplo: se deixar
Form1, será bem fácil encontrar outro aplicativo feito em Delphi que possua uma janela com
este nome, o que causaria problema.
dbiSaveChanges(Query1.Handle);
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 84/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
with Form do
case Vert of
1: Form.Top := 0;
2: Form.Top := (R.Bottom - R.Top - Height) div 2;
3: Form.Top := R.Bottom - Height;
end;
end;
{ - Coloque dois TEdit's: Edit1 e Edit2;
- Coloque um TButton e altere o evento OnClick deste
conforme abaixo:
}
procedure TForm1.Button1Click(Sender: TObject);
begin
FormPos(Form1, StrToInt(Edit1.Text), StrToInt(Edit2.Text));
end;
Observações
Para
Edit'stestar, execute
e clique estepara
no Button exemplo
ver oeresultado.
experimente digitar
O Edit1 números
indica de 1 horizontal
a posição a 3 em ambos os
(esquerda,
centro e direita) e o Edit2 indica a posição vertical (topo, centro e em baixo).
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 85/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
{--Coloque
Coloqueno noForm1
Form1um
umTButton
TEdit (Edit1)
- Altere o evento OnClick do Button1 conforme abaixo: }
Para
(não testar
precisavocê deverá executar
os dois-pontos). Apósodigitar,
exemplo e digitar
clique no Edit a letra do drive a ser testado
no Button1.
interface
uses Forms, IniFiles, SysUtils, Messages, Windows;
procedure
procedure tbLoadFormStatus(Form:
tbSaveFormStatus(Form: TForm;
TForm; const Section: string);
const Section: string);
implementation
procedure tbSaveFormStatus(Form: TForm; const Section: string);
var
Ini: TIniFile;
Maximized: boolean;
begin
Ini := TIniFile.Create(ChangeFileExt(
ExtractFileName(ParamStr(0)),'.INI'));
try
Maximized := Form.WindowState
Ini.WriteBool(Section, 'Maximized',=Maximized);
wsMaximized;
if not Maximized then begin
Ini.WriteInteger(Section, 'Left', Form.Left);
Ini.WriteInteger(Section, 'Top', Form.Top);
Ini.WriteInteger(Section, 'Width', Form.Width);
Ini.WriteInteger(Section, 'Height', Form.Height);
end;
finally
Ini.Free;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 86/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
end;
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 87/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 88/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
{
* Crie um novo Projeto. Este certamente terá o Form1.
* Adicione um novo Form (Form2).
* Coloque no Form2 dois botões TBitBtn.
* Mude a propriedade Kind do BitBtn1 para bkOK.
* Mude a propriedade Kind do BitBtn2 para bkCancel.
* Vá no menu "Project/Options" na aba "Forms" e passe o
Form2 de "Auto-create Forms" para "Available Forms".
* Abra o arquivo Project.dpr (menu Project/View Source).
* Altere o conteúdo deste arquivo conforme abaixo:
}
program Project1;
uses
Forms, Controls,
Unit1 in 'Unit1.pas' {Form1},
Unit2 in 'Unit2.pas' {Form2};
{$R *.RES}
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 89/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
var
F: TForm2;
begin
F := TForm2.Create(Application);
try
ifApplication.Initialize;
F.ShowModal = mrOK then begin
Application.CreateForm(TForm1, Form1);
Application.Run;
end;
finally
F.Free;
end;
end.
Observações
O Form2 do exemplo é o Form de LogOn. Este deverá ser preparado para que se possa
escolher o usuário, digitar a senha, etc.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 90/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Por exemplo:
{No
Coloque
eventonoOnClick
Form dois Botões: BotaoOcultar
do BotaoOcultar escreva: e} BotaoExibir.
procedure TForm1.BotaoOcultarClick(Sender: TObject);
var
Janela: HWND;
begin
Janela := FindWindow('Shell_TrayWnd', nil);
if Janela > 0 then
ShowWindow(Janela, SW_HIDE);
end;
{ No evento OnClick do BotaoExibir escreva: }
procedure TForm1.BotaoExibirClick(Sender: TObject);
var
Janela: HWND;
begin
Janela := FindWindow('Shell_TrayWnd', nil);
if Janela > 0 then
ShowWindow(Janela, SW_SHOW);
end;
{ Execute e teste, clicando em ambos os botões }
Observações
A tarefa
mas isto mais
é fácildifícil é descobrir
se você o nome de classe
usar o TBWinName. da janela
Pegue-o no linkda barra dede
download tarefa do Windows,
www.ulbrajp.com.br/usuario/tecnobyte O resto é usar as APIs do Windows para manipulação
de Janelas. Veja a pergunta nº 18.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 91/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 92/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
MouseParaControle(btnOk);
end;
Observações
A função "MouseParaControle" recebe um parâmetro do tipo TControl. Isto significa que você
poderá passar para ela qualquer controle do Delphi, tais como: TEdit, TButton,
TSpeedButton, TPanel, etc. Pode ser até mesmo o próprio Form.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 93/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Observações
Isto pode ser útil quando queremos usar fonte da impressora quando for uma matricial ou
fonte do Windows quando for uma Jato de Tinta ou Laser. Veja também a pergunta nº 10.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 94/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 95/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
{ Somente Delphi4
if Tabela.Exists then}{ Se a tabela já existe... }
Exit;
{***}
{ Cria a tabela }
Tabela.FieldDefs.Add('Codigo', ftInteger, 0, true);
Tabela.FieldDefs.Add('Nome', ftString, 30, true);
Tabela.FieldDefs.Add('DataNasc', ftDate, 0, false);
Tabela.FieldDefs.Add('RendaMes', ftCurrency, 0, false);
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 96/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
{ Cria os Índices }
Tabela.AddIndex('ICodigo', 'Codigo', [ixPrimary, ixUnique]);
Tabela.AddIndex('INome',
{ etc, etc, etc } 'Nome', [ixCaseInsensitive]);
finally
Tabela.Free;
end;
end;
Observações
Para verificar se o arquivo já existe na versão 3 ou anterior do Delphi, você deverá usar a
função "FileExists" do Delphi.
ifShowMessage('O
FileExists('c:\carta.doc')
arquivothen
existe')
else
ShowMessage('O arquivo não existe');
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 97/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 98/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
with ComboBox1 do
begin
Visible := False;
R.TopLeft := frmMain.ScreenToClient(
StringGrid1.ClientToScreen(R.TopLeft));
R.BottomRight := frmMain.ScreenToClient(
StringGrid1.ClientToScreen(R.BottomRight));
SetBounds(R.Left, R.Top, R.Right - R.Left, R.Bottom - R.Top);
;
end
with StringGrid1 do
if (TopRow <= Row) and (TopRow + VisibleRowCount > Row) then
ComboBox1.Show;
end
;
In essence, the main routine here is the stringgrid's OnDrawCell event handler. Of course, I
also set the stringgrid's DefaultRowHeight property to be the same height as the
combobox. In addition, the stringgrid's OnTopLeftChanged event handler is used to hide the
combobox when the user scrolls out of view. Also, when the user selects an item from the
combobox, simply place the text in the current Col/Row.
You can also do a couple other little tricks such as setting the stringgrid's Objects[] property
to point to the combobox, as well as possibly setting the combobox's Parent property to
point to the stringgrid. However, I've had problems with the Parent approach -- namely, that
of dropping down the listbox associated with the combobox.
StringGrid1.Canvas.Brush.Style:=bsSolid;
{You could add some color here, if desired:}
Case Col of
1: StringGrid1.Canvas.Brush.Color:=clRed;
2: StringGrid1.Canvas.Brush.Color:=clWhite;
3: StringGrid1.Canvas.Brush.Color:=clBlue;
end
;
{Erase data}
StringGrid1.Canvas.FillRect(Rect);
{Get text in a PChar string}
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 99/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
StrPCopy(TempPString,StringGrid1.Cells[Col,Row]);
{DrawText--see other options in Windows API help;
Change the DT_LEFT to DT_RIGHT for right justified txt!}
DrawText(StringGrid1.Canvas.Handle,TempPString,-1,Rect,DT_LEFT);
;
end
{...}
Inc(C);
;
end
end ;
;
end
begin
if SizeOf(ColOrder) div SizeOf(i) <> Grid.ColCount then Exit;
for i := 0 to High(ColOrder) do
if (ColOrder[i] < 0) or (ColOrder[i] >= Grid.ColCount) then Exit;
j := 0;
Sorted := False;
repeat
Inc(j);
with Grid do
for i := 0 to RowCount - 2 do
if Sort(i, i + 1) > 0 then
begin
TMoveSG(Grid).MoveRow(i + 1, i);
Sorted := False;
;
end
until Sorted or (j = 1000);
Grid.Repaint;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 100/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
;
end
// Show Word
// Word anzeigen
WordApp.Visible := True;
// Add a new Doc
// Neues Dok einfügen
NewDoc := WordApp.Documents.Add;
// Add a Table
// Tabelle einfügen
WordTable := NewDoc.Tables.Add(WordApp.Selection.Range, iCols, iRows);
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 101/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
// ...
// Cleanup...
WordApp := Unassigned;
NewDoc := Unassigned;
WordTable := Unassigned;
;
end
for i := 0 to SG.RowCount - 1 do
begin
Dest.Lines.Add(' <tr>');
for p := 0 to SG.ColCount - 1 do
begin
SStyle1 := '';
SStyle2 := '';
if fsbold in SG.Font.Style then
begin
SStyle1 := SStyle1 + '<b>';
SStyle2 := SStyle2 + '</b>';
;
end
if fsitalic in SG.Font.Style then
begin
SStyle1 := SStyle1 + '<i>';
SStyle2 := SStyle2 + '</i>';
;
end
if fsunderline in SG.Font.Style then
begin
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 102/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
// Example, Beispiel
procedure TFormCSVInport.Button6Click(Sender: TObject);
begin
SGridToHtml(StringGrid1, Memo1, 1);
Memo1.Lines.SaveToFile('c:\test.html');
;
end
uses
ComObj;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 103/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
// Hide Excel
XLApp.Visible := False;
// Add new Workbook
XLApp.Workbooks.Add(xlWBatWorkSheet);
Sheet := XLApp.Workbooks[1].WorkSheets[1];
Sheet.Name := ASheetName;
// Fill up the sheet
Sheet.Range[RefToCell(1, 1), RefToCell(AGrid.RowCount,
AGrid.ColCount)].Value := Data;
// Save Excel Worksheet
try
XLApp.Workbooks[1].SaveAs(AFileName);
Result := True;
except
// Error ?
;
end
finally
// Quit Excel
if not VarIsEmpty(XLApp) then
begin
XLApp.DisplayAlerts := False;
XLApp.Quit;
XLAPP := Unassigned;
Sheet := Unassigned;
;
end
end ;
;
end
// Example:
thenShowMessage('StringGrid saved!');
;
end
{**************************************************************}
{2. Without OLE }
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 104/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
;
end
// Example:
{**************************************************************}
{3. Code by Reinhard Schatzl }
uses
ComObj;
if ACount = 0 then
Result := Chr(Ord('A') + ColID - 1) + IntToStr(RowID);
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 105/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
if ACount = 1 then
Result := 'A' + Chr(Ord('A') + APos - 1) + IntToStr(RowID);
try
//Excelsheet anzeigen
if ShowExcel = False then
XLApp.Visible := False
else
XLApp.Visible := True;
//Workbook hinzufügen
for M := 1 to BookCount do
begin
XLApp.Workbooks.Add(xlWBATWorksheet);
//Sheets anlegen
for N := 1 to SheetCount - 1 do
begin
XLApp.Worksheets.Add;
;
end
;
end
//Sheet ColAnzahl feststellen
if Grid.ColCount <= 256 then
SheetColCount := Grid.ColCount
else
SheetColCount := 256;
//Sheet RowAnzahl feststellen
if Grid.RowCount <= 65536 then
SheetRowCount := Grid.RowCount
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 106/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
else
SheetRowCount := 65536;
//Sheets befüllen
for M := 1 to BookCount do
begin
for N := 1 to SheetCount do
begin
//Daten aus Grid holen
Data := VarArrayCreate([1, Grid.RowCount, 1, SheetColCount], varVaria
nt);
for I := 0 to SheetColCount - 1 do
for J := 0 to SheetRowCount - 1 do
if ((I + 256 * (N - 1)) <= Grid.ColCount) and
((J + 65536 * (M - 1)) <= Grid.RowCount) then
Data[J + 1, I + 1] := Grid.Cells[I + 256 * (N - 1), J + 65536 *
(M - 1)];
//-------------------------
XLApp.Worksheets[N].Select;
XLApp.Workbooks[M].Worksheets[N].Name := SheetName + IntToStr(N);
//Zellen als String Formatieren
XLApp.Workbooks[M].Worksheets[N].Range[RefToCell(1, 1),
RefToCell(SheetRowCount, SheetColCount)].Select;
XLApp.Selection.NumberFormat := '@';
XLApp.Workbooks[M].Worksheets[N].Range['A1'].Select;
//Daten dem Excelsheet übergeben
Sheet := XLApp.Workbooks[M].WorkSheets[N];
Sheet.Range[RefToCell(1, 1), RefToCell(SheetRowCount, SheetColCount)]
.Value :=
Data;
end ;
;
end
//Save Excel Worksheet
try
for M := 1 to BookCount do
begin
SaveFileName := Copy(FileName, 1,Pos('.', FileName) - 1) + IntToStr(M)
+
Copy(FileName, Pos('.', FileName),
Length(FileName) - Pos('.', FileName) + 1);
XLApp.Workbooks[M].SaveAs(SaveFileName);
;
end
Result := True;
except
// Error ?
;
end
finally
//Excel Beenden
if (not VarIsEmpty(XLApp)) and (ShowExcel = False) then
begin
XLApp.DisplayAlerts := False;
XLApp.Quit;
XLAPP := Unassigned;
Sheet := Unassigned;
;
end
end ;
;
end
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 107/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
//Example
procedure TForm1.Button1Click(Sender: TObject);
begin
//StringGrid inhalt in Excel exportieren
//Grid : stringGrid, SheetName : stringgrid Print, Pfad : c:\Test\ExcelFile
.xls, Excelsheet anzeigen
StringGridToExcelSheet(StringGrid, 'Stringgrid Print', 'c:\Test\ExcelFile.x
ls', True);
;
end
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 108/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
GERAL
Strings
copy - Copia uma substring, dentro de uma string
Var
vtexto, Copia: String;
begin
vtexto := copy(vtexto,2,2);
Copia Edit1.Text ; // descobriu
// copiaode
valor de texto
vtexto, apartir da segunda letra dois caracteres
Label1.Caption := Copia; // o label exibira as duas letras
end;
// delete - Deleta uma substring dentro de uma string.
ex: Delete (Mystring, 2,1) // delete da variável mysring, na segunda posição, 1 caractere
insert - Insereuma substring em uma string .
ex: Insert ("z", mystring, 1 ) //insere a letra z no começo da string
Inttostr - Converte um valor inteiro para string.
ex: MyString := Inttostr(Shape1.top) //A variaável mystring recebe o valor top do componente Shape1
length - Retorna o número de caracteres de uma string
ex: canvas.textout ( 10, 10, ' Número de caracteres =' + InttoStr (length MmyString )));
//exibe o número de caracteres contido em uma string.
Lowercase - Converte para menúsculos os caracteres alfabétiocs de uma string;
Lowercase( 'SORTE' ); // tranformar para 'sorte'
Pos - Esta função retorna um valor integer correspondente a posição de uma string dentro de uma outra string.
Var
VPalavra : string;
VNumero : Integer;
Begin
VPalavra := ' Pernambuco ' ;
VNumero := Pos ( ' a ' , VPalavra ) ; // Numero retorna o valor 5
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 109/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Button1. Top := N ;
End ;
// Se a variável C tiver valor diferente de 0 significa que ouve erra na conversção. ( ex : O texto do Edit não é um
número intéiro válido )
Declarando uma strings:
var
marte: string //declaração
terra: string simples
[5] //delimitado 5 caracteres para a string
venus: shortstring //string de menos de 256 caracteres
Format
//Para coloca zeros a esquerda dos números encontrados.
%5 mostra o valor da variável inteira "VNum"
// .5d por que são 5 caracteres
Edit1.text:= Format('%5.5d',[VNum]);
Mensagens
Menssagem simples
ShowMessage( ' texto da menssagem ' );
Caixa de messagem
MessageDlg( ' aviso ' , mtInformation, [mbOk], 0 );
if MessageDlg('Quer sair do programa',mtInformation,[mbYes,mbNo],0) = mrYes then
Form1.close;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 110/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
DataModule1.Tb_Alunos.Delete;
INPUTBOX e INPUTQUERY
INPUTBOX
//A linha abaixo exibe uma caixa de diálogo onde digitamos um valor que será exibido em um label
Label1.Caption := InputBox('digite','integer','');
<B.INPUTQUERY<
//Sensível b>e minúsculas. Veja abaixo dois exemplos.
à maiúsculas
Exemplo1
procedure TForm1.Button3Click(Sender: TObject);
var
NS: string;
clickOK: Boolean; // clickok foi inventado
begin
NS := 'Nome fixo';
Label1.Caption := NS;
clickOK := InputQuery('Input Box', 'digite', NS);
if clickOK then
Label1.Caption := 'The new string is ''' + NS + '''';
end;
Exemplo2
var
r : string
; begin
inputQuery( ' ver ' , ' senha ' , r );
if r = ' s ' then
shape1.Visible := true
else
showmessage( ' senha errada ' );
end;
Tratando Erros
Deletando um registro
try
DMAgenda.tbAgenda.Delete;
except
On E:EDBEngineError do
ShowMessage('Registro em uso por outro USUÁRIO. Exclusão Cancelada';
end;
Datas Inválidas
Try
StrtoDate(Edit1.text);
except
on EconvertError do
ShowMessage('Data Inválida');
end;
Centralizar um componete No evento OnResize digite
No evento abaixo, toda vez que o form sor redimencionado, o Button ficara no centro
Button1.Top := Form1.ClientHeight div 2 - Button1.Height div 2;
Button1.Left := Form1.ClientWidth div 2 - Button1.Width div 2;
Senhas
Colocar senha numa tabela Paradox //...e retirar em tempo de execução:
Session.AddPassword('Senha-Da-Tabela');
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 111/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
...
Session.RemovePassword;
outra opção...
Session.AddPassword('Senha');
Table1.Active := True;
// vincule o Table1 ao Session>
findfield
Contador : Integer;//colocar em na área var ou uses
var // no evento onClick do botão OK
s : TstringField; //unit db
begin
s:= DataModlule1.Table1.findfield('senha')as TstringField; // procura na coluna senha
if s.value <> Edit1.text then
begin
ShowMessage('senha invalida');
inc(contador);
if Contador = 3 then
begin
ShowMessage('vc teve 3 chances');
formPrincipal.Close;
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 112/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
exit;
formSenha.Close;
formPrincipal.Enabled := true;
end;
#0=Null #8=Backspace
#27=Escape #32=Espaço#13=Enter
#127=Delete
//fazer o Enter, substituir o Tab...
if key = #13 then
Edit1.SetFocus; // o Edit recebe o foco
Caracteres especiais
// declare uma constante com os caracteres especiais... Const
chrEspecial : Set of Char =['@','#','$','%'];
//no evento OnKeyPress, digite:
If key in ChrEspecial then
ShowMessage('esta letra é especial');
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 113/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
if OpenPictureDialog1.Execute then
image1.Picture.LoadFromFile (OpenPictureDialog1.fileName) ; // carrega uma imagem no componente
FontDialog
if FontDialog1.Execute then
begin
Memo1.Font := Font;// poderia ser um RichEdit
end;
ou...
with FontDialog1 dobr> begin
Font := Label1.Font;
if Execute then
Label1.Font := Font;
end;
colordialog
if colordialog1.Execute then
begin
with ColorDialog1 do
begin
Color := Label1.Color;
ou...
if Execute then
Label1.Color := Color;
end;
RichEdit.Color := Color;
end;
PrintDialog
PrintDialog1.Execute;
Label1.caption := timetostr(time);
Label1.caption := datetostr(date);
// Somar uma data
var
Ts1, ts2 : TTimeStamp;
Data1, Data2 : TDateTime;
Dias : Integer;
begin
Date1 := StrtoDate(edit1.text);
Date2 := StrtoDate(edit2.text);
Ts1 := DateTimetoTimeStamp(Data1);
Ts2 := DateTimetoTimeStamp(Data2);
Dias := Ts2.Date - Ts1.Date;
Edit3.Text := InttoStr(Dias);
if Dias > 10 then
ShowMessage('Passaram-se 10 dias');
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 114/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
O Dia da Semana
function DayOfWeek(Data:TDataTime):Integer;
Ex.:Label1.Caption:= 'Data e Hora Atual' + DateTimeToStr(Now);
- Retorna o dia da semana em um inteiro de 1 a 7.
Métodos e Propriedades
Show // exibe um form do Form
Hide // esconde um form mas não o descarrega
Print // imprime um form
SetFocus // establece o foco para um form ou componente
BringtoFront // envia o frente
Texto em um form
canvas.textout(0,0,'Este texto aparece no form. Top e Left zerados');
Form Elíptico
No evento OnCreate do form, digite:
var hR : THandle;
begin
{cria uma form de formato elíptico}
hR := CreateEllipticRgn (0,0,Width,Height);
SetWindowRgn (Handle,hR,True);
end;
Obs. Também é bom alterar a propriedade BorderStyle para bsNone. O tamanho da elípse é definido pelo tamanho
do form.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 115/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Diretório do aplicativo
// No evento OnCreate, digite:
var
PathName: string;
begin
PathName := ExtractFilePath (ParamStr (0));
Label1.Caption := 'Estamos em: '+ PathName;
end;
O Componente TComboBox
Para abrir um TComboBox sem clica-lo, digite:
ComboBox1.DroppedDown := True;
end;
Último passo: Destruir a instância com o método destrutor
MinhaLista.Destroy;
Trabalhando com Case... of
Criando seleções
var Seletor : char;
begin
Seletor := 'C';
Case Seletor of
'A' : ShowMessage('Escolhido A');
'B' : ShowMessage('Escolhido B');
'C' : Begin
Showmessage('Escolhido C');
Halt; // encerra o programa
end;
else// caso não seja uma destas letras
ShowMessage('Não escolhido um destes ítems');
end;
Trabalhando com Case II
Case RadioGroup1.ItemIndex of
0 : Form2.BorderStyle := bsDialog;
1 : Form2.BorderStyle := dbNone;
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 116/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Usando o Repeat
var
N : String;
begin
Repeat;
N := Inputbox('GetNumber',
Until N:= '7'; 'Insira um número','');
end;
Atribuir Mesmo Valor para Vários Edits em um Form
for i := 0 to ComponentCount - 1 do
if Components[i] is TEdit then
TEdit(Components[i]).Text := Valor;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 117/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
BANCO DE DADOS
SENHAS
// Senha usadas na maioria dos programas
No Campo Var, Digite :
Contador : integer;
Vs : string
Em Usues, Digite : DB;
No botão Ok, digite
if not Table1.FindKey([edit1.Text]) then // o campo chave é Nome
begin
ShowMessage('UsuárioDesconhecido');
inc (contador);
if contador = 4 then
begin
ShowMessage(‘ Sua chance acabou');
FmPrincipal.Close;
end;
Exit; (* para encerrar *)
end;
vs:=Table1.findField(‘Login’).asString;
if vs<>Edit2.text then
begin
ShowMessage('Senha Errada');
inc(contador);
if contador=4 then
fmPrincipal.close;
Edit2.setFocus;
exit;
end;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 118/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
fmPrincipal.Enabled:=True;
fmSenha.close;
Criando Tabelas
Através da função FieldDefs.ADD. Parâmetros: nome do campo, tipo, Tamanho, Chave_Primária.
Procedure Cria_Tabela(Alias,Nome_Tabela:String);
Begin
With TTable.Create(Application) do
begin
Active := False;
DatabaseName :=Alias;
TableName := Nome_Tabela;;
TableType := ttDefault;
FieldDefs.Add('CODCLI', ftString, 5, False);
FieldDefs.Add('NOMCLI', ftString, 40, False);
FieldDefs.Add('DATCAD', ftDate, 0, False);
CreateTable;
Free;
end;
end;
Como Usar:
procedure TForm1.Button1Click(Sender: TObject);
begin
Cria_Tabela('C:\Temp','Alunos.db');
end;
LOCALIZAR
//nesta caixa de diálogo, o campo nome tem que ser o primeiro
var // uma variárvel tem que ser criada.
nome : string;
Nome : = inputbox( ' Localizar ' , ' digite o nome ' , ' ' ) ;
if nome <> ' ' then
begin
if not table1.findkey ( [ nome ] ) then
showmessage ( ' nome não encontrado ' ) ;
end;
Simplificando: Table1.findkey([edit1.text])
ou
table1.setkey;
table1.fields[0].AsString := Edit1.text;
Table1.GotoKey;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 119/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
table1NomeCliente.AsString := Edit1.Text;
Table1.GotoNearest;
.
// Procurar em um índice primário ou secundário
Table1.IndexName := 'Nome'
Table1.Open;
Table1.SetKey;
Table1Nome_Cliente.AsString := Edit1.Text;
Table1.GotoNearest;
FindKey
//Procura um nome em um campo. ( no primeiro campo ).
// No evento OnClick do Botão Ok, digite
begin
if not DataModule.tsenha.FindKey ( [ editNome.text ] ) then
beguin
ShowMessage ( ' senha desconhecida ' );
Exit;
end ;
Exceções
Access violation
Decrare a constante:
const
ChaveViolada = 9729;
No evento OnPostError da tabela, digite:
if (E is EDBEngineError) then
if (E as EDBEngineError).Error[0].Errorcode = ChaveViolada then
begin
Table1.Cancel;
ShowMessage('este código já existe');
end;
abort
Outras exceções
if(E is EDBEngineError) then
with EDBEngineError(E) do
case Errors[0].ErrorCode of
DBIERR_KEYVIOL: ShowMessage('Cliente já cadastrado.');
DBIERR_REQDERR: ShowMessage('Campo obrigatório não preenchido.');
end
else
ShowMessage('Erro no banco de dados:' + #13#13 + E.Message);
Action := daAbort;
0 SQL
//Seleciona todos os campos da tabela cliente
Select * from cliente
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 120/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
//Selecione todos os campos da tabela produto organizado por nproduto em ordem descendente
Select * from produto order by nproduto desc
//Classificar em ordem descendente (Z a A, 9 a 0), adicione a palavra reservada DESC ao final de cada campo
SELECT Sobrenome, Salário FROM Funcionários ORDER BY Salário DESC, Sobrenome;
//Esse exemplo ordena, primeiro, por categoria ID e depois por nome do produto.
SELECT CategoriaID, ProdutoNome, PreçoUnit FROM Produtos ORDER BY CategoriaID, NomeProduto;
//Selecione os campos descrição, preço e o valor de preço + 20 de tabela produto onde nproduto = 004
Select descrição, preço, preço + 20 from produto where nproduto = 004
//Selecione todos os campos da tabela Leitores onde o campo nome seja iguas a 'João'
Select * from Leitores where Nome = 'João Cabral'
//Selecione todos os campos da tabela cliente onde o campo nome inicie com Vis* desprezando os outros caracteres
Select * from cliente where nome LIKE 'Vis%'
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 121/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
//Qual seria o salário se cada funcionário recebesse um aumento de 10 porcento. Não altera o valor original dos
salários.
SELECT Sobrenome, Salário AS Atual, Salário * 1.1 AS Proposto FROM Funcionários;
//Coloca o título Nome no topo da coluna "Sobrenome". O título Salário, no topo da coluna "Salário".
SELECT Sobrenome AS Nome, Salário FROM Funcionários;
Select nproduto from pedido/ produto where nPedido = 1
Select nproduto from pedido / produto where nProduto = 2
Select nproduto from pedido / produto where npedido = 1 UNION ALL Select
nproduto From pedido/ produto where nProduto = 2
Selecione todos os campos da tabela pedido onde o campo npedido esteja entre 2 e 5
Select * from pedido where nproduto IN ( 2,5 )
//Conta o número de registros que têm uma entrada no campo "CódigoPostal" e nomeia o campo retornado como
"Tcp".
SELECT Count(CódigoPostal) AS Tcp FROM Clientes;
// O exemplo abaixo habilita o usuário a ver as informações de salário (mesmo que não tenha outra permissão para
ver a tabela Folha de Pagamentos) desde que o proprietário da consulta tenha tal permissão:
SELECT Sobrenome, Nome, Salário FROM Funcionários ORDER BY Sobrenome WITH OWNERACCESS
OPTION;
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 122/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
//Para cada registro, mostra Sobrenome e Salário no primeiro e último campos. A seqüência de caracteres "tem um
salário
SELECT de"Sobrenome,
é retornada'tem
como
umosalário
campode',
do meio deFROM
Salário cada registro.
Funcionários;
//Cria uma lista de nomes de departamentos únicos e o número de funcionários em cada um destes departamentos.
SELECT Departamento, Count([Departamento]) AS Tbc FROM Funcionários GROUP BY Departamento;
//Para cada título de função único, calcula o número de funcionários do departamento de Vendas que têm este
título.
SELECT Título, Count(Título) AS Tbc FROM Funcionários WHERE Departamento = 'Vendas' GROUP BY Título;
//Calcula o número de itens em estoque para cada combinação de número e cor do item.
SELECT Item, Sum(Unidades) AS Tbc FROM ItensEmEstoque GROUP BY Item, Cor;
//Seleciona todos os registros de "Novos Clientes" e os adiciona à tabela "Clientes" (quando não são designadas
colunas individuais, os nomes das colunas das tabelas SELECT devem corresponder exatamente aos da tabela
INSERT INTO).
INSERT INTO Clientes SELECT [Novos Clientes].* FROM [Novos Clientes];
//Muda os valores no campo "RelatórioPara" para 5 para todos os registros de funcionários que atualmente têm
valores de RelatórioPara de 2.
UPDATE Funcionários SET RelatórioPara = 5 WHERE RelatórioPara = 2;
//Reduz o PreçoUnit de todos os produtos não suspensos fornecidos pela Tokyo Traders em 5 porcento. As tabelas
"Produtos" e "Fornecedores" têm uma relação um para vários.
UPDATE Fornecedores INNER JOIN Produtos ON Fornecedores.FornecedorID = Produtos.FornecedorID
SET PreçoUnit = PreçoUnit * .95 WHERE NomeEmpresa = 'Tokyo Traders' AND Suspenso = No;
//Exclui todos os registros de funcionários cujo título seja Estagiário. Quando a cláusula FROM inclui apenas uma
tabela, não é necessário indicar o nome da tabela na instrução DELETE.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 123/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
//Exclui todos os registros de funcionários cujo título seja Estagiário e que também tenham um registro na tabela
"FolhadePagamento". As tabelas "Funcionários" e "FolhadePagamento" têm uma relação um por um.
DELETE Funcionários.* FROM Funcionários INNER JOIN FolhaDePagamento
ON Funcionários.FuncionárioID = FolhadePagamento.FuncionárioID
WHERE Funcionários.Título = 'Estagiário';
//Retorna todos os produtos cujo preço unitário é maior que o preço de qualquer produto vendido com um desconto
de 25 % ou mais:
SELECT * FROM Produtos WHERE PreçoUnit > ANY (SELECT PreçoUnit FROM PedidoDetalhes
WHERE Desconto >= .25);
//Retorna os nomes dos funcionários cujos salários sejam iguais ou superiores à média de salários de todos os
funcionários na mesma função. Para a tabela Funcionários é dada o alias "T1":
SELECT Sobrenome, Nome, Título, Salário FROM Funcionários AS T1 WHERE Salário >= (SELECT
Avg(Salário) FROM Funcionários WHERE T1. T1.Título = Funcionários.Título) Order by Title;
//Lista o nome, título e salário de todos os representantes de vendas cujos salários sejam superiores aos de todos os
gerentes e diretores.
SELECT Sobrenome, Nome, Título, Salário FROM Funcionários WHERE Título LIKE "*Repr Vendas*"
AND Salário > ALL
(SELECT Salário FROM Funcionários WHERE (Título LIKE "*Gerente*") OR (Título LIKE
"*Diretor*"));
//Lista o nome e preço unitário de todos os produtos cujo preço unitário seja igual ao do Licor de Cacau.
SELECT NomeProduto, PreçoUnit FROM, Produtos WHERE PreçoUnit = (SELECT PreçoUnit FROM
[Produtos]
WHERE NomeProduto = "Licor de Cacau");
//Lista a empresa e o contato de cada empresa de todos os clientes que fizeram pedidos no segundo trimestre de
1995.
SELECT NomeContato, NomeEmpresa, ContatoTítulo, Fone FROM Clientes
WHERE ClienteID IN (SELECT ClienteID FROM Pedidos
WHERE DataPedido BETWEEN #1/04/95# AND #1/07/95#);
//Lista os funcionários cujo salário seja maior que a média dos salários de todos os funcionários.
SELECT Sobrenome, Nome, Título, Salário FROM Funcionários T1 WHERE Salário >= (SELECT
AVG(Salário) FROM Funcionários
WHERE Funcionários.Título = T1.Título) ORDER BY Título;
//Seleciona o nome de todos os funcionários que tenham registrado pelo menos um pedido. Isto também poderia ser
feito com INNER JOIN.
SELECT Nome, Sobrenome FROM Funcionários AS E WHERE EXISTS (SELECT * FROM Pedidos AS O
WHERE O.FuncionárioID = E.FuncionárioID);
//Altera o campo Efetuado do arquivo de serviços para 2 caso o mesmo tenha parecer técnico da entidade
encaminhanhamento diferente de nulo.
UPDATE servico SET efetuado = 2 WHERE numero_servico = ANY (SELECT servico.numero_servico
FROM servico INNER JOIN encaminhamento ON (servico.numero_servico = encaminhamento.
numero_servico)
AND (servico. ano_servico = encaminhamento.ano_servico) WHERE (((servico.efetuado) Is Null) AND
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 124/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Query - Parametros
// digitar no SQL do query
{ Select * from geral where Nome like :ord
Na properties Params colocar : Name := Ord, Value := %}
Fields
var s : string;
begin
s := Table1.Fields [0].FieldName; //retorna o nome do primeiro campo da tabela
s := Table1.Fields [1] .asString; // retorna o conteúdo 2º campo da tabela
s := Table1.FieldByName( ' nome ' ).AsString; //retorna o valor na coluna 'nome'
s := Table1['Nome'] ; //retorna o valor do compo selecionado
BOOKMARKS
//guardar uma posição no registro
var
BM :tBookMark;
{...}
// Grava um Registro
if bm = nil then // se bm está vazio então...
bm := table1.GetBookMark; // marque um
ou
if BookMark = nil then
BookMark := Table1.GetBookMark;
{++}
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 125/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
begin
table1.GotoBookMark(BookMark) // vá para o marcado
end;
ou..
if BM <> nil then
begin
BM := table1.GetBookMark(BM);
{++}
//limpa da memória o registro guardado
if BookMark <> nil then // se o BookMark não está vazio então faça..
begin
Table1.FreeBookMark (BookMark); // libere o marcado..
BookMark := nil; // deixe-o vazio
end;
ou
if bm <> nil then
begin
Table1.FreeBookMark (bm);
bm := nil;
end;
// conjunto de comandos
if BookMark < > nil then
begin
table1.GotoBookMark(BookMark);
Table1.FreeBookmark(BookMark);
BookMark := nil;
end;
Gravar em um banco de dados
tabel1.edit;// abre o dataset
tabel1['senha'] := 'Marvel'; // edita 'Marvel' no campo senha
tabel1.post; // grava a informação
Filter
Table1.Filtered := false;
Table1.Filter := 'idade > 30 ' ;
(ex: Table1.Filter := 'Nota1>=' + '''' + Edit1.text + ''''';)
Table1.Filtered := true;
Filter II
Table1.SetRangeStart;
Table1.FieldbyName('código') := 100; //Table1Codigo.AsInteger := 100
Table1.KeyExclusive := False;
Table1.SetRageEnd;
Table1.FieldbyName('Codigo') := 200; //Table1Codigo.AsInteger := 200
Table1.KeyExclusive := true;
Table1.ApplyRange
// Aplicar um filtro usando um CHECKBOX
Table1.Filtered := checkbox1.Checked;
// No componente TABLE, no evento OnFilterRecord
Accept := Table1['Nome']= Edit1.Text
// Um botão pode seguir para o próximo ítem procurado
Table1.FindNext
Soma
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 126/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 127/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
MULTIMIDIA
Imagem no Form
Colocar uma figura bmp, no form sem o Picture
var
BitMap : TBitMap;
Begin
BitMap : = TBitMap.Creat ;
With BitMap do
Biguin
LoadFromFile( ' c : \ figura . bmp' ) ;
Transparent := true ;
Form1. Canvas . Draw (50,50, bitMap);
end:
end;
//Desktop, imagem no form
//Procedure TForm E. FormResize(Sender: tobject);
Var
R : TRect ;
DC : HDc ;
Canv : TCanvas ;
Begin
R : = Rect (0,0, Screen.Width, Screen.Height);
DC : = GetWindowDC (GetDeskTopWindow);
Canv := TCanvas.Create;
Canv . Handle := DC;
Canvas . CopyRect(R,Canv,R);
ReleaseDC (GetDeskTopWindow, DC);
end;
O componente TMediaPlayer
Para ouvir um som
With MediaPlayer1 do
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 128/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
begin
FileName := 'c:\bettoven.wav'; // pode ser um Mid
Open;
Play;
end;
Para
with ver um *.avi nodoform...
MediaPlayer1
begin
FileName := 'c:\super.avi';
Open;
Display := Form2;
Form2.Show;
Play;
end;
Arquivos Texto
Carregando o texto em um RichEdit
RichEdit1.Lines.LoadFromFile('c:\aviso.txt');
//colocando cores
ReachEdit1.Font.Color := clGreen;
Estilos de Texto
//testo em negrito
if CheckNegrito.Checked then //Para o botão Negrito
Memo1.Font.Style := Memo1.Font.Style + [fsBold] // coloca em estilo negrito
else
Memo1.Font.Style := Memo1.Font.Style - [fsBold]; // retira o estilo negrito
//Memo1.Font.Style := Memo1.Font.Style + [fsItalic] // Para o botão Itálico
//Memo1.Font.Style := Memo1.Font.Style + [fsUnderline] // Para o botão Sublinhado
Alinhamento do texto
{taLeftJustify, taCenter, taRightJustify}
Label1.Alignment := taLeftJustify;
Trabalhando com Arquivos .INI
Acrescente a unit inifiles na guia uses
//declare uma variável inifile:
ArqIni: TIniFile;
//no evento OnCreate, do form, digite:
ArqIni := TIniFile.Create('c:\windows\ArqIni.ini');
lendo um arquivo ini
// lendo um valor string:
EditString.Text := ArqIni.ReadString('String', 'texto', '');
//lendo um valor inteiro:
EditString.Top := ArqIni.ReadInteger('Integer', 'altura', 0);
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 129/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Movimento
fazer um panel ter seu texto em movimento
var
texto : string;
begin
texto : = panel1.caption;
panel1.caption := copy(texto,2,length (texto)) + texto[1];
end;
ColorGrid
Form1.Color := ColorGrid1.ForegroundColor ; //botão esquerdo do mouse
Form1.Color := ColorGrid1.BackgroundColor ;// botão direito do mouse
Movendo Arquivos
var
origem, destino : string;
begin
origem := 'c:\delete\faq.txt';
destino:= 'c:\games\faq.txt';
if not copyfile(pchar(origem),pchar(destino),true) then
showMessage ( 'problemas com' + origem + 'para' + destino)
MOVENDO UM OBJETO
// Coleque em um objeto ( ex: um Button)
// Na guia VAR, digite
MouseDownSpot : TPoint;
Capturing : bool;
// No evento OnMouseDown
SetCapture(Button1.Handle);
Capturing := true;
MouseDownSpot.X := x;
MouseDownSpot.Y := Y;
// No evento OnMouseMove
if Capturing then
begin
Button1.Left:= Button1.Left-(MouseDownSpot.x -x);
Button1.Top:= Button1.Top - (MouseDownSpot.y -y);
end;
// No evento OnMouseUp
if Capturing then
begin
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 130/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
ReleaseCapture;
Capturing := false;
Button1.Left := Button1.Left - (MouseDownSpot.x -x);
Button1.Top := Button1.Top - (MouseDownSpot.y - y);
end;
Randomize
//A linha de comando abaixo faz o label exibir aleatóriamente um número de 1 a 100
Label1.Caption := InttoStr(Random(100));
Hint
//colocar no evento OnCreate do form principal..
Application.HintColor := clYellow; // define a cor de todos os hints
Application.HintPause := 200; // define o tempo de espera de um hint
btnOk.ShowHint := true; // habilita a exibição de um hint
btnOk.Hint := 'Clique aqui'; // define o texto
Edit1.hint := 'Primeira linha' + #13 + 'segunda linha'; //Hint com quebra de linha
Criar um componente em tempo de execução
var
PictImg1 : TImage; //declarando um TImage
begin
PictImg1 := tImage.Create(self);
PictImg1.Height := 200;
pictImg1.Width := 200;
PictImg1.Picture.LoadFromFile('C:\1.bmp');
PictImg1.parent := Self;
end;
Progess Bar
Criando um ProgressBar em tempo de execução
//Declare a procedure abaixo
procedure TestProgress(Form: TForm; Count: SmallInt);
var
ProgressBar1: TProgressBar;
i: SmallInt;
begin
ProgressBar1 := TProgressBar.Create(Form);
try
ProgressBar1.Parent := Form;
ProgressBar1.Align := alBottom;
ProgressBar1.Min := 0;
ProgressBar1.Max := Count;
ProgressBar1.Step := 1;
for i := 1 to Count do
ProgressBar1.Stepit;
ShowMessage('Now the ProgressBar control will be freed');
finally
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 131/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
ProgressBar1.Free;
end;
end;
Finalmente, facha a chamada para o ProgessBar...
TestProgress(Self, 1000);
form2.show;
O Componente TCalendar
Calendar1.PrevYear;// para exibir o ano anterior
Calendar1.NextYear;// para exibir o proximo ano
Calendar1.PrevMonth;// para exibir o mês anterior
Calendar1.NextMonth;// para exibir o próximo mês
Calendar1.CalendarDate := CalendarDate - 1; // vai para um dia anterior
Calendar1.CalendarDate := CalendarDate + 1; // vai para o proximo dia
Arquivos .ini
Acresentar em Uses: IniFiles;
Declare:
Tini : TInifile;
Criando do arquivo. No evento OnCreate:
Tini := TInifile.Create('c:\super.ini');
Lendo em um arquivo...
Label1.Caption := Tini.ReadString('Label','titulo','');
Label1.top := Tini.ReadInteger('Label','top',0);
Label1.visible := Tini.ReadBool('Label','ver',true);
Gravando em um arquivo...
Tini.WriteString('label','titulo','Olá Mundo');
Tini.WriteInteger('label','top',10);
Tini.WriteBool('label','ver',true);
Ao findar tudo...
IniFile.Destroy;
Dias da semana
var
WeekDay : array[1..7] of string;
DayNo : integer;
QDay : string;
begin
weekday[1] := 'domingo
weekday[2] := 'segunda';
weekday[3] := 'ter‡a';
weekday[4] := 'quarta';
weekday[5] := 'quinta';
weekday[6] := 'sexta';
weekday[7] := 'sabado'; DayNo := DayofWeek(Date); // pega numero do dia da semana..
// a mensagem exibe o valor do array na posi‡Æo n. da semana
ShowMessage('O dia ‚: ' + WeekDay[DayNo]);
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 132/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
else
ShowMessage('O ano não esta configurado para quatro dígitos.');
end;
// botão dois..
if FFrame <> nil then
FFrame.Free;
FFrame := TFrame2.Create(pnlParent);
FFrame.Align := alClient;
FFrame.Parent := pnlParent;
INTERNET
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 133/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
TCP1.LocalIP = '127.0.0.1')
ShowMessage('Não then
existe conexão')
else
ShowMessage('Existe Conexão')
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 134/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Original : http://www.drbob42.com/delphi4/actions.htm
A new and handy feature of Delphi 4 - also present in C++Builder 4 by the way - is the
TActionList component, found in the "Standard" tab of the component palette. With an
ActionList, we can group and manage "actions" (event handling code) between different
components and even re-use them among different applications!
This article shows how to use Actions and ActionLists - without writing a single line of Delphi
or C++ code - and contains some nice gotchas too...
Using TActionList
Start a new application, and drop a TActionList component on the Form. Right-click with the
mouse on the ActionList1 component to get the Action List Editor. The Action List Editor
shows the action categories, and for each action category the individual actions that are
available for the current application.
We can define new actions, or select a number of existing (standard) actions. The latter can
be done by right-clicking with the mouse in the Action List Editor, and selecting the New
Standard Action menu:
This will give us a new dialog with the (current) list of standard actions. Note that we can
select more than one action at the same time by holding down the Ctrl key and clicking on
each individual item (see left figure below).
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 135/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
After we click on OK, we return to the Action List Editor which now shows two categories
(Edit and Window) and four actions in total (Copy, Cut and Paste for the Edit categories, and
MinimizeAll for Windows) - see right figure above.
It's now time to add some controls to the Form and connect them to these actions.
Control Action
Go to the Win32 tab of the component palette, and drop a ToolBar component on the form.
Right-click on it and select "New Button" to add a new button. Repeat this until you have
four buttons next to each other on the toolbar (tip: you may want to insert a separator
between the third and fourth button).
Now, click the left button, and set its Action property to EditCopy1. Set the Action property
of the second button to EditCut1, and the third button to EditPaste1. Finally, set the Action
property of the last button to WindowMinimizeAll1.
Before we compile and run this application, let me remind you that we now have four fully
functional toolbar buttons without having written a single line of code. That's because we're
using standard behavior that's already been provided to us as "standard" re-usable Actions.
But it gets even better, because we can share these actions with multiple components.
Go back to the Standard tab of the component palette, and drop a TMainMenu component
on the Form. Double-click on it (to get into the Menu Designer). Right-click on the Menu
Designer select "Insert from Template" and pick the Edit menu template. This gives us a list
of 10 menu items, while we only need three (Cut, Copy and Paste), but at least it saves us
some typing. You can easily remove the menu items that you don't need, by the way.
Go to the Cut1 menu item, and set its Action property to EditCut1. Set the Action property
of the Copy1 menu item to EditCopy1, and let Paste1 point to EditPaste1. We're now almost
ready to compile and run our application, but we need one more thing. Let's drop three
normal buttons on the form (again from the Standard tab), and connect them to EditCut1,
EditCopy1 and EditPaste1 like we've done twice before already. Note that the "regular"
buttons automatically get captions with "Cut", "Copy" and "Paste", where the speedbuttons
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 136/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
on the ToolBar remain empty (their Hint property it set, but not their caption).
A solution to this potential (confusing) problem can be implemented by assigning an
ImageList to the ActionList, so each action can get associated with a specific image. To do
this, drop a TImageList (from the Win32 tab) on the Form, and right-click on it to fill it with
some images. Set the Images property of the ActionList a component to ImageList1, and
double-click again on the ActionList to get the Action List Editor where we can now specify
which image should be used by which individual Action item by setting the ImageIndex for
each individual action:
Note that the speedbuttons on the toolbar and the images next to the menu texts still don't
show the images from the ImageList1 at design-time. In order to let them "share" the same
images, we must set the Images property of the ToolBar1 component to ImageList1, and do
the same with the Images property of the MainMenu1 component. The ImageIndex
properties will now be copied from the index belonging to the Action components, so each
action will look the same on a speedbutton or as a menu-item.
The really final thing we need to do is drop a TEdit component on the Form (after all, we
would need some Edit control to test the Cut, Copy and Paste actions with, right?). After
that, your application should resemble the following screenshot (at least a little bit, I hope):
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 137/138
5/12/2018 4941493DicasParaDelphi-slidepdf.com
Action!
Now, save your work, compile and run the application. Initially, all buttons and menu-items
will be disabled, meaning that we cannot Cut or Copy text, nor can we Paste any text at this
time. If your clipboard is filled with some text, and you select the editbox, then the Paste
buttons and menu-item get enabled automatically (at the same time). We can then select
the Paste menu, for example, and the text from the clipboard will be pasted inside the
editbox. As soon as we select some text from the editbox, the Cut and Copy buttons and
menu-items will get enabled as well (we can only Cut and Copy selected text, of course).
We can now click on the Cut or Copy speedbutton in the toolbar to get the effect we want.
Note that each Action items somehow "knows" when it can be executed (in our case: when
the current control is an editbox or memo, and - in case of Cut and Copy - whether or not
any text is currently selected). The Action items can enable and disable all controls that are
associated with them as soon as something changes that influences them (like selecting
text, or moving the focus from the editbox to another control, for example).
Problems?
This all seems to work fine. However, if you try to Cut, Copy or Paste text inside the editbox
using any of the "normal" buttons, then you will find that they do not appear to work. For
some reason, the big Cut button doesn't cut the text, nor does the bit Paste button paste it.
In fact, they only seem to result in de-selecting the text in the editbox (if any text was
selected), and moving the focus away... Strange!
Well, that last piece of information, regarding the focus, should have been a subtle hint: the
buttons take away the focus before the Action can be executed. In other words: the
Action expects an editbox to have the focus, but by the time the Action it executed, it's the
button that has the focus (if not for the Button's Click method that fires the action, the
action wouldn't even have been fired, since giving the button the focus means disabling the
action and all controls associated with the action).
Of course, the workaround is never to use any controls that can get the focus (like a
TButton which has a Windows handle), so the focus will never be list when we click on any
Action-bound control again. This is not something that's documented too well, however, and
I must admit that even I fell into this trap (while performing my Delphi 4 Workout in
London, by the way), so be aware.
http://slidepdf.com/reader/full/4941493-dicas-para-delphi 138/138