Escolar Documentos
Profissional Documentos
Cultura Documentos
private
Bmp: TBitmap;
Bmp:= TBitMap.Create;
try
Bmp.LoadFromFile('c:\teste\arquivo.bmp');
Canvas.Draw(0,0, Bmp);
finally
Bmp.Free;
end;
Problema:
Solução:
Problema:
Solução:
{ Exemplo de uso: }
Problema:
Solução:
{ Exemplo de uso:
- Coloque um TButton e um TEdit;
- No OnClick do Button1 coloque o código abaixo;
- Execute, digite 'Caption' no Edit1 e clique em Button1.
}
procedure TForm1.Button2Click(Sender: TObject);
begin
ShowMessage(PropType(Button1, Edit1.Text));
end;
Observações
Verdadeiramente não sei exatamente onde poderíamos aplicar esta dica, mas divulguei-a
porque achei interessante. Acredito que o Object Inspector use algo parecido.
Problema:
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.
{ Exemplo de uso: }
Problema:
Solução:
Edit1.Text := tbFormataCEP(Edit1.Text);
Observações
Para formatar outros códigos como CPF, CGC, etc., pode-se usar a mesma idéia.
Problema:
Solução:
public;
Cancelar: boolean;
Form1.Cancelar := true;
try
{ Antes de começar o processamento }
Form2.Caption := 'Processamento demorado...';
Form2.Show;
end;
finally
Form2.Close;
end;
Observações
Não se esqueça de que o Form1 precisa usar Form2 e vice-versa.
Problema:
Solução:
private
procedure WMHotkey(var Msg: TWMHotkey); message WM_HOTKEY;
{
- Coloque um botão no form;
- Altere o evento OnClick do botão conforme abaixo:
}
ShowMessage(S);
end else
ShowMessage('Erro ao abrir chave do Registro');
finally
Reg.Free;
end;
end;
Observações
A unit Dialogs foi acrescentada no uses somente para podermos usar a procedure
ShowMessage.
144 - Obter a célula de um StringGrid que está sob o
cursor do mouse
Inclua na seção uses: Windows
{ Exemplo de uso:
- Coloque um botão no form;
- Altere o evento OnClick deste botão como abaixo:
}
{ Para testar:
- Execute o programa;
- Posicione o cursor do mouse sobre alguma célula do
StringGrid;
- Pressione TAB até chegar ao botão e pressione ENTER;
- O resultado será mostrado no Caption do form;
}
Observações
Note que a procedure MouseCell usa um valor negativo (-1) para coluna e linha se o mouse
não estiver sobre o StringGrid.
143 - Limpar todas as células de um StringGrid
Problema:
Criei um editor de textos no Delphi. Agora gostaria que o
Windows Explorer usasse este editor para abrir arquivos com
a extensão .dpg e .dan. Como fazer?
Solução:
{ *.dpg }
Reg.OpenKey('.dpg', true);
Reg.WriteString('', 'ArquivoDaniel');
Reg.CloseKey;
{ *.dan }
Reg.OpenKey('.dan', true);
Reg.WriteString('', 'ArquivoDaniel');
Reg.CloseKey;
finally
Reg.Free;
end;
end;
- Coloque um TMemo;
- No evento OnShow do Form coloque o código abaixo:
Problema:
Solução:
Problema:
Solução:
Antes de enviar seu relatório, faça assim:
RegisterServiceProcess(GetCurrentProcessID, 1);
RegisterServiceProcess(GetCurrentProcessID, 0);
SendMessage(Application.Handle, WM_SYSCOMMAND,
SC_MONITORPOWER, 0);
Sleep(5000); { Aguarde 5 segundos }
SendMessage(Application.Handle, WM_SYSCOMMAND,
SC_MONITORPOWER, -1);
Observações
Este recurso pode não funcionar dependendo da configuração do sistema.
{ Para abrir }
mciSendString('Set cdaudio door open wait', nil, 0, handle);
{ Para fechar }
mciSendString('Set cdaudio door closed wait', nil, 0, handle);
private
procedure WMMove(var Msg: TWMMove); message WM_MOVE;
Para testar:
Solução:
SetForegroundWindow(Application.Handle);
ShowMessage('Teste');
Problema:
Solução:
Para testar:
- Execute este aplicativo;
- Clique no botão;
- Vá 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:
Solução:
Clipboard.AsText := S;
end;
Para testar:
- Execute este aplicativo;
- Clique no botão;
- Vá em outro aplicativo (ex: MS-Word) e mande colar (Ctrl+V).
127 - Criar sub-diretório no diretório do EXE
Inclua na seção uses: FileCtrl, SysUtils
Problema:
Solução:
Exemplo de uso:
RegisterServiceProcess(GetCurrentProcessID, 1);
Application.ShowMainForm:=False;
Problema:
Solução:
private
procedure ManipulaExcecoes(Sender: TObject; E: Exception);
Problema:
Solução:
Simles. Veja:
Problema:
Solução:
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:
Gostaria de colocar algums bitmaps em uma DLL e usá-los em
tempo de execução. É possível fazer isto em Delphi?
Solução:
{$R BMPS.RES}
library DLLBmp;
end.
Problema:
Solução:
private
procedure WMNCHitTest(var Msg: TMessage);
message WM_NCHitTest;
public
{ Public declarations }
end;
implementation
{$R *.DFM}
- Exemplos de uso:
Problema:
A função IntToHex do Delphi converte inteiro para
hexadecimal. O que preciso, no entanto, é fazer o contrário,
ou seja, converter de hexadecimal para inteiro. Existe
isto pronto no Delphi ou terei que escrever uma função
para isto?
Solução:
var
I: integer;
begin
I := StrToInt('$' + Edit1.Text);
{...}
end;
Observações
No Delphi, um número na notação decimal deve iniciar com o símbolo $.
Problema:
Solução:
- Exemplo de uso:
{ Pressiona F2 }
keybd_event(VK_F2, 0, 0, 0);
keybd_event(VK_F2, 0, 0, 0);
{ Exemplos de uso: }
{ Exemplos de uso: }
if tbKeyIsDown(VK_CONTROL) then
{ Tecla Ctrl pressionada }
if tbKeyIsDown(VK_MENU) then
{ Tecla Alt pressionada }
if tbKeyIsDown(VK_SHIFT) then
{ Tecla Shift pressionada }
if tbKeyIsDown(VK_F2) then
{ Tecla F2 pressionada }
Observações
Qualquer tecla pode ser verificada. Para isto basta saber o código virtual (Virtual Key Code)
da tecla.
107 - Verificar o estado de NumLock e CapsLock
Inclua na seção uses: Windows
{ 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.
Problema:
private
procedure DBGridClick(Sender: TObject);
implementation
{$R *.DFM}
with Edit2 do
if Text <> '' then
Text := AnsiUpperCase(Text[1]) + Copy(Text, 2, Length(Text));
if Edit1.SelStart = 0 then
Key := AnsiUpperCase(Key)[1]
else
Key := AnsiLowerCase(Key)[1];
Problema:
Vejamos:
var
PrevCur: TCursor;
begin
PrevCur := Screen.Cursor;
try
Screen.Cursor := crHourGlass;
{ Coloque aqui as instruções do processamento }
finally
Screen.Cursor := PrevCur;
end;
end;
Observações
Existem diversos outros cursores pré-definidos no Delphi. Dê uma olhada na propriedade
Cursor de um componente visual para ver uma lista de todos eles. Você poderá também
criar o seu próprio cursor.
Coloque no Form:
- três edits;
- dois botões.
Reg := TRegistry.Create;
try
{ Define a chave-raiz do registro }
Reg.RootKey := HKEY_CURRENT_USER;
{ Se existir o valor... }
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 := DateToStr(Ficha.DataCadastro);
end else
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: não grave dados muito extensos no Registro do Windows (ex: imagens), pois isto
prejudicará o desempenho do sistema.
if Reg.ValueExists('Numero') then
Edit1.Text := IntToStr(Reg.ReadInteger('Numero'))
else
ShowMessage('Não existe valor com o nome "Numero"');
if Reg.ValueExists('Nome') then
Edit2.Text := Reg.ReadString('Nome')
else
ShowMessage('Não existe valor com o nome "Nome"');
end else
ShowMessage('Não existe a chave no registro');
finally
Reg.Free;
end;
end;
Observações
User o aplicativo RegEdit.exe do windows para ver o registro. Cuidado para não alterar as
configurações do Windows!
Key := AnsiUpperCase(Key)[1];
Key := AnsiLowerCase(Key)[1];
Para testar:
- Coloque um Edit no form;
- Coloque um Button;
- No evento OnClick do botão coloque o código abaixo:
if tbStrIsDate(Edit1.Text) then
ShowMessage(Edit1.Text + ' é data válida.')
else
ShowMessage(Edit1.Text + ' NÃO é data válida.');
Problema:
Coloque no Form:
- Um DataSource
- Um Table
- Um DBGrid
- Um 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.
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.
90 - Limpar um campo tipo data via programação
Table1.FieldByName('Data').Clear;
{ ou }
Table1.FieldByName('Data').AsString := '';
Observações
Podemos usar este recurso para limpar também campos numéricos, string, etc.
Q := TQuery.Create(nil);
try
Q.DatabaseName := Table.DatabaseName;
Q.SQL.Add('select max(' + FieldName + ') from ' + Table.TableName);
Q.Open;
try
Table.FieldByName(FieldName).AsInteger := Q.Fields[0].AsInteger +1;
finally
Q.Close;
end;
finally
Q.Free;
end;
end;
{ Personalizada }
ShellAbout(Handle, 'NomePrograma',
'Direitos autorais reservados a'#13'Fulano de Tal',
Application.Icon.Handle);
var
Lin, Col: Cardinal;
begin
tbGetMemoLinCol(Memo1, Lin, Col);
{ ... }
end;
var
Lin, Col: integer;
begin
Lin := Memo1.CaretPos.y;
Col := Memo1.CaretPos.x;
{...}
end;
if IsZoomed(Form1.Handle) then
{ Form1 está maximizado }
else
{ Form2 NÃO está maximizado }
Observações
Veja a pergunta n. 78.
{ Solução 1: }
var
Pt: TPoint;
Rct: TRect;
begin
GetCursorPos(Pt);
GetWindowRect(Button1.Handle, Rct);
if PtInRect(Rct, Pt) then
{ Está no botão }
else
{ NÃO está no botão }
end;
{ 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.
if IsIconic(Application.Handle) then
{ Minimizado }
else
{ Não minimizado }
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.
{ Problema:
1 - Promissória
2 - Duplicata
3 - Boleto
Solução:
Isto pode ser feito de várias formas, mas aqui vou mostrar
como resolver usando o evento OnGetText do TField. Vejamos:
Top := 0;
Left := 0;
Width := Screen.Width;
Height := Screen.Height;
Observações
Nos testes que fiz, mesmo com a barra de tarefas marcada como "Sempre Visível",
funcionou perfeitamente. Fiz os testes usando o Win95. Talvez em novas versões, possa
apresentar problemas.
{ Problema:
Solução:
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 a aplicação deram alguns problemas de conversão do
tipo de Dado. Analisando o problema percebi que havia
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 tudo de novo. Porém quando tentei instalar
novamente o Interbase Server, surpresa, o 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
Obrigado,
Alexsandro Pimenta
Xenon Software Comércio e Serviços Ltda
apepper@uol.com.br
Solução:
Sr. Alexsandro,
Renata Oliva
Inprise Support Center
{ Para inverter: }
SwapMouseButton(true);
{ 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.
{ No form:
- Coloque um memo;
- Coloque um edit;
- Coloque um botão e escreva seu OnClick como abaixo: }
{ Da unidade C: }
SetVolumeLabel('c:\', 'NovoLabel');
{ Da unidade atual: }
SetVolumeLabel(nil, 'NovoLabel');
Observações
Veja a pergunta nº 66.
64 - Saber quais as unidades de disco (drives) estão
presentes
Inclua na seção uses: Windows
ValorReal := 135.54658;
{ Duas casas }
X := Trunc(ValorReal * 100) / 100; // X será 135.54
{ Três casas }
X := Trunc(ValorReal * 1000) / 1000; // X será 135.5465
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.
{ Tamanho da fonte }
c10cpi = #18;
c12cpi = #27#77;
c17cpi = #15;
cIExpandido = #14;
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 e apenas um exemplo, mas voce podera adapta-lo ' +
'a sua realidade conforme 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.
const
SHFMT_ID_DEFAULT = $FFFF;
{ Opções de formatação }
SHFMT_OPT_QUICKFORMAT = $0000; { Formatação rápida }
SHFMT_OPT_FULL = $0001; { Formatação completa }
SHFMT_OPT_SYSONLY = $0002; { Copia sistema }
{ Códigos de errros }
SHFMT_ERROR = $FFFFFFFF; { Ocorreu erro }
SHFMT_CANCEL = $FFFFFFFE; { Foi cancelado }
SHFMT_NOFORMAT = $FFFFFFFD; { Não formatou }
function SHFormatDrive(Handle: HWND; Drive, ID, Options: Word):
LongInt; stdcall; external 'shell32.dll' name 'SHFormatDrive'
program Project1;
uses
Forms, Windows,
Unit1 in 'Unit1.pas' {Form1};
{$R *.RES}
var
ExtendedStyle : Integer;
begin
Application.Initialize;
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
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);
Table1.RecNo()
PlaySound('C:\ArqSom.wav', 1, SND_ASYNC);
Observações
Troque o nome do arquivo (C:\ArqSom.wav) pelo arquivo desejado.
WinExec('command.com /c programa.exe',sw_ShowNormal);
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;
type
TChars = set of Char;
Observações
Se quizer usar este função em outras unit's, coloque a declaração do tipo TChars na seção
interface. Coloque aí também uma declaração da função FilterChars. E não se esqueça da
cláusula uses.
37 - Colocar zeros à esquerda de números
Observações
"S" precisa ser uma variável string.
35 - Copiar arquivos
end;
{ Verifica o Word }
if FindWindow('OpusApp', nil) > 0 then
ShowMessage('O Word está aberto')
else
ShowMessage('O Word NÃO está aberto');
{ Verifica o Excell }
if FindWindow('XLMAIN', nil) > 0 then
ShowMessage('O Excell está aberto')
else
ShowMessage('O Excell NÃO está aberto');
end;
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.
program Project1;
uses
Forms, Windows,
Unit1 in 'Unit1.pas' {DPGFormPrinc};
{$R *.RES}
var
Handle: THandle;
begin
Handle := FindWindow('TDPGFormPrinc', nil);
if Handle <> 0 then begin { Já está aberto }
Application.MessageBox('Este programa já está aberto. A cópia ' +
'anterior será ativada.', 'Programa já aberto', MB_OK);
if not IsWindowVisible(Handle) then
ShowWindow(Handle, SW_RESTORE);
SetForegroundWindow(Handle);
Exit;
end;
Application.Initialize;
Application.CreateForm(TDPGFormPrinc, DPGFormPrinc);
Application.Run;
end.
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(Table1.Handle);
dbiSaveChanges(Query1.Handle);
interface
uses Forms, IniFiles, SysUtils, Messages, Windows;
implementation
end.
{
Em cada formulário que deseja salvar/restaurar:
- Inclua na seção uses: uFormFunc
- No evento OnShow digite:
tbLoadFormStatus(Self, Self.Name);
- No evento OnClose digite:
tbSaveFormStatus(Self, Self.Name);
}
Observações
O arquivo INI terá o nome do executável e extensão INI e será salvo no diretório do
Windows. A palavra Self indica o Form relacionado com a unit em questão. Poderia ser, por
exemplo, Form1, Form2, etc. Onde aparece Self.Name poderá ser colocado um nome a sua
escolha. Este nome será usado como SectionName no arquivo INI e deve ser idêntico no
evento OnShow e OnClose de um mesmo Form, porém para cada Form deverá ser usado um
nome diferente.
{
* 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}
var
F: TForm2;
begin
F := TForm2.Create(Application);
try
if F.ShowModal = mrOK then begin
Application.Initialize;
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.
Por exemplo:
procedure CriaTabelaClientes;
var
Tabela: TTable;
begin
Tabela := TTable.Create(Application);
try
Tabela.DatabaseName := 'C:\';
{ ou Tabela.DatabaseName := 'NomeAlias'; }
Tabela.TableName := 'Clientes.DB';
Tabela.TableType := ttParadox; { ou ttDBase }
{ 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);
Tabela.FieldDefs.Add('Ativo', ftBoolean, 0, true);
{ etc, etc, etc }
Tabela.CreateTable;
{ Cria os Índices }
Tabela.AddIndex('ICodigo', 'Codigo', [ixPrimary, ixUnique]);
Tabela.AddIndex('INome', 'Nome', [ixCaseInsensitive]);
{ etc, etc, etc }
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.
if DirectoryExists('C:\MEUSDOCS') then
ShowMessage('O diretório existe')
else
ShowMessage('O diretório não existe');
if FileExists('c:\carta.doc') then
ShowMessage('O arquivo existe')
else
ShowMessage('O arquivo não existe');
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}
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;
{...}
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;
end;
// Show Word
// Word anzeigen
WordApp.Visible := True;
// Add a Table
// Tabelle einfügen
WordTable := NewDoc.Tables.Add(WordApp.Selection.Range, iCols, iRows);
// ...
// 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
SStyle1 := SStyle1 + '<u>';
SStyle2 := SStyle2 + '</u>';
end;
Text := sg.Cells[p, i];
if Text = '' then Text := ' ';
Dest.Lines.Add(' <td width="' + IntToStr(sg.ColWidths[p]) +
'" height="' + IntToStr(sg.RowHeights[p]) +
'"><font color="#' + IntToHex(sg.Font.Color, 6) +
'" face="' + SG.Font.Name + '">' + SStyle1 +
Text + SStyle2 + '</font></td>');
end;
Dest.Lines.Add(' </tr>');
end;
Dest.Lines.Add(' </table>');
Dest.Lines.Add('</body>');;
Dest.Lines.Add('</html>');
end;
// Example, Beispiel
procedure TFormCSVInport.Button6Click(Sender: TObject);
begin
SGridToHtml(StringGrid1, Memo1, 1);
Memo1.Lines.SaveToFile('c:\test.html');
end;
uses
ComObj;
// Example:
{**************************************************************}
{2. Without OLE }
// Example:
{**************************************************************}
{3. Code by Reinhard Schatzl }
uses
ComObj;
if ACount = 0 then
Result := Chr(Ord('A') + ColID - 1) + IntToStr(RowID);
if ACount = 1 then
Result := 'A' + Chr(Ord('A') + APos - 1) + IntToStr(RowID);
//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;
//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;
GERAL
Strings
copy - Copia uma substring, dentro de uma string
Var
vtexto, Copia: String;
begin
vtexto := Edit1.Text ; // descobriu o valor de texto
Copia := copy(vtexto,2,2); // copia de 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;
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]);
Delete - Ex:
Delete(MyString) // deleta da variável MyString, na segunda posição, um caractere
Insert - Ex:
Insert ('z',MyString,1) // Insere a letra z no começo da String
InttoStr - Ex:
MyString := InttoStr(Shape1.top)//A variável MyString recebe o valor top do componente Shape1
Mensagens
Menssagem simples
ShowMessage( ' texto da menssagem ' );
Caixa de messagem
MessageDlg( ' aviso ' , mtInformation, [mbOk], 0 );
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< b>
//Sensível à maiúsculas e minúsculas. Veja abaixo dois exemplos.
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;
Senhas
Colocar senha numa tabela Paradox //...e retirar em tempo de execução:
Session.AddPassword('Senha-Da-Tabela');
...
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;
exit;
formSenha.Close;
formPrincipal.Enabled := true;
end;
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');
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;
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.
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.
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;
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;
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;
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
//Selecione todos os campos da tabela produto onde nproduto seja igual a 004
Select * from produto where nproduto = 004
//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%'
//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;
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;
//O número de funcionários e os salários médio e máximo.
SELECT Count(*) AS [Total de Funcionários], Avg(Salário) AS [Salário Médio], Max(Salário) AS [Salário
Máximo] FROM Funcionários;
//Para cada registro, mostra Sobrenome e Salário no primeiro e último campos. A seqüência de caracteres "tem um
salário de" é retornada como o campo do meio de cada registro.
SELECT Sobrenome, 'tem um salário de', Salário FROM 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];
Seleciona todos os estagiários de "Estagiários" que foram contratados há mais de 30 dias e adiciona seus registros
à tabela "Funcionários".
INSERT INTO Funcionários SELECT Estagiários.* FROM Estagiários WHERE DataContrato < Now() - 30;
//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.
DELETE *FROM Funcionários WHERE Título = 'Estagiário';
//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
((encaminhamento.parecer_tecnico) Is Not Null))
GROUP BY servico.numero_servico ORDER BY servico.numero_servico);
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
ListBox
// esta rotina exibe em um listbox os campos de uma tabela
var
i: Integer;
begin
ListBox1.Clear;
for i := 0 to table1.fieldcount - 1 do
Listbox1.items.add(table1.fields[i].fieldname);
end;
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;
{++}
{++}
//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
Soma
// RecordCount, conta quantos registros ha na Tabela
Label1.Caption := InttoStr(Table1.Recordcount);
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;
A Tecla Pressionada
//No evento OnKeyDown, digite:
Label1.Caption := Format('O código da tecla é: %d', [Key]);
O componente TMediaPlayer
Para ouvir um som
With MediaPlayer1 do
begin
FileName := 'c:\bettoven.wav'; // pode ser um Mid
Open;
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
//testo em negrito II
if BoldButton.Down then
CurrText.Style := CurrText.Style + [fsBold]
else
CurrText.Style := CurrText.Style - [fsBold];
end;
function TMainForm.CurrText: TTextAttributes;
begin
if Editor.SelLength > 0 then Result := Editor.SelAttributes
else Result := Editor.DefAttributes;
end;
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);
//lendo um valor boolean
EditString.Visible := ArqIni.ReadBool('Boolean', 'visivel',False);
//lendo um arquivo ini em um meno:
Memo1.Lines.LoadFromFile('c:\inicial.ini');
gravando em um arquivo .ini
//gravando um valor string
ArqIni.WriteString('String', 'texto', EditString.Text);
//gravando um valor inteiro
ArqIni.WriteInteger('Integer', 'altura', SpinEdit1.value);
// gravando um valor boolean
ArqIni.WriteBool('Boolean', 'visivel', CheckBox1.Checked);
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
ReleaseCapture;
Capturing := false;
Button1.Left := Button1.Left - (MouseDownSpot.x -x);
Button1.Top := Button1.Top - (MouseDownSpot.y - y);
end;
Arquivos Help
// digite a linha abaixo para chamar um arquivo help
WinHelp(Form1.handle, 'c:\Ajuda.hlp', HELP_CONTENTES,0);
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
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
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]);
// botão dois..
if FFrame <> nil then
FFrame.Free;
FFrame := TFrame2.Create(pnlParent);
FFrame.Align := alClient;
FFrame.Parent := pnlParent;
INTERNET
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).
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
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):
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.