|
Exemplos |
|
se você tiver algum exemplo ou
dica e quizer me enviar, ou se algum exemplo deste
não der certo, me mande um e-mail
para que eu possa corrigir, porque alguns exemplos aqui citados não são de minha
autoria, portanto não posso garantir a qualidade dos mesmos.
|
01- Criar um nova tabela
a partir de uma estrutura de outra tabela
O exemplo abaixo
mostra como você pode a partir de uma tabela que já
está sendo utilizada pelo seu sistema, criar uma nova tabela com a mesma
estrutura já vazia.
implementation
uses DB,DBTables;
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var
TabOrigem, TabDestino: TTable;
begin
TabOrigem := TTable.create(self);
with TabOrigem do
begin
DatabaseName := 'ViewFarma';
TableName := 'Bairros.db';
open;
end;
TabDestino := TTable.create(self);
with TabDestino do
begin
DatabaseName := 'ViewFarma';
TableName := 'Bairros2.db';
FieldDefs.Assign(TabOrigem.FieldDefs);
IndexDefs.Assign(TabOrigem.IndexDefs);
CreateTable;
end;
TabOrigem.close;
end;Topo |
02- Retornar o dia da
Semana
O Delphi tem uma
função chamada DayOfWeek que permite que você possa
saber qual o dia da semana de uma determinada data. Para testar este
exemplo inclua o código abaixo no evento OnClick de um componente
Button, exatamente como mostra abaixo:
var
Form1: TForm1;
implementation
{$R *.DFM}
// Evento OnClick do componente Button
procedure TForm1.Button1Click(Sender: TObject);
begin
Case DayofWeek(Date) of
1:ShowMessage(Hoje é domingo);
2:ShowMessage(Hoje é segunda-feira);
3:ShowMessage(Hoje é terça-feira);
4:ShowMessage(Hoje é quarta-feira);
5:ShowMessage(Hoje é quinta-feira);
6:ShowMessage(Hoje é sexta-feira);
7:ShowMessage(Hoje é sábado);
end;
end; Topo |
03- DBGrid
- Verifica os registros selecionados
O exemplo abaixo mostra como você pode verificar quais os registros que estão
selecionados no componente DBGrid. Para selecionar vários registros você deve primeiro
alterar a sub-propriedade dgMultiSelect que faz parte da propriedade Options para True. var
Form1: TForm1;
implementation
{$R *.DFM}
// Evento OnClick do componente BitBtn
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
Table1.First;
While not Table1.Eof do
begin
if DBGrid1.SelectedRows.IndexOf(Table1.BookMark) >= 0
then
ShowMessage(Registro selecionado);
Table1.Next;
end;
end;
Topo |
04 - Configurar o
século no Delphi
Veja como
configurar o século no Delphi A variável TwoDigitYearCenturyWindow indica quantos anos a
partir do ano corrente ainda vai ser contado como do mesmo século, isto é, 1900.
Por exemplo, o número 2 indica que a partir do ano corrente toda data com 2 anos de
diferença será contada como do ano 2000.
Ano corrente = 98
TwoDigitYearCenturyWindow := 2;
95 será igual a 2095
Topo |
05 - Verifica
se o Delphi esta sendo executado
// Evento
OnClick do componente Button
procedure TForm1.Button1Click(Sender: TObject);
begin
if FindWindow('TAppBuilder', Nil) <> 0 Then
ShowMessage(' O Delphi está rodando.');
end; Topo |
06 - Pintar o fundo
do Formulário
Veja abaixo como
pintar o fundo de um form com uma imagem BMP sem utilizar um componente Image. unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure FormPaint(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
BitMap : TBitMap;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
Begin
BitMap := TBitMap.Create;
BitMap.LoadFromFile(c:\windows\floresta.bmp);
end;
procedure
TForm1.FormPaint(Sender: TObject);
var X, Y, W, H: LongInt;
begin
with Bitmap do
begin
W := Width;
H := Height;
end;
Y := 0;
while Y < Height do
begin
X := 0;
while X < Width do
begin
Canvas.Draw(X, Y,
Bitmap);
Inc(X, W);
end;
Inc(Y, H);
end;
end;
end.
Topo |
07- Adicionar
o campo em uma tabela Paradox
unit Unit1; interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Grids, DBGrids, Db, DBTables, BDE, DBCtrls, Menus, ComCtrls,
Buttons ;
type
TForm1 = class(TForm)
DataSource1: TDataSource;
DBGrid1: TDBGrid;
Button1: TButton;
Table1: TTable;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var Form1: TForm1;
type
ChangeRec = packed record
szName: DBINAME;
iType: Word;
iSubType: Word;
iLength: Word;
iPrecision: Byte;
end;
var MyChangeRec: ChangeRec;
procedure AddField(Table:
TTable; NewField: ChangeRec);
implementation
{$R *.DFM}
procedure
TForm1.Button1Click(Sender: TObject);
begin
MyChangeRec.szName := NovoCampo;
MyChangeRec.iType := fldPDXCHAR;
MyChangeRec.iSubType:=0;
MyChangeRec.iLength := 45;
MyChangeRec.iPrecision := 0;
Table1.Close;
Table1.Exclusive := True;
Table1.Open;
AddField(Table1, MyChangeRec);
Table1.Close;
Table1.Exclusive := False;
Table1.Open;
end;
procedure AddField(Table:
TTable; NewField: ChangeRec);
var Props: CURProps;
hDb: hDBIDb;
TableDesc: CRTblDesc;
pFlds: pFLDDesc;
pOp: pCROpType;
B: byte;
begin
if Table.Active = False then
raise EDatabaseError.Create(A tabela precisa estar
aberta);
if Table.Exclusive = False then
raise EDatabaseError.Create(A tabela precisa estar aberta
em modo
Exclusivo);
Check(DbiSetProp(hDBIObj(Table.Handle), curxltMODE, integer(xltNONE)));
Check(DbiGetCursorProps(Table.Handle, Props));
pFlds := AllocMem((Table.FieldCount + 1) * sizeof(FLDDesc));
FillChar(pFlds^, (Table.FieldCount + 1) * sizeof(FLDDesc), 0);
Check(DbiGetFieldDescs(Table.handle, pFlds));
for B := 1 to
Table.FieldCount do
begin
pFlds^.iFldNum := B;
Inc(pFlds, 1);
end;
try
StrCopy(pFlds^.szName, NewField.szName);
pFlds^.iFldType := NewField.iType;
pFlds^.iSubType := NewField.iSubType;
pFlds^.iUnits1 := NewField.iLength;
pFlds^.iUnits2 := NewField.iPrecision;
pFlds^.iFldNum := Table.FieldCount + 1;
finally
Dec(pFlds, Table.FieldCount);
end;
pOp := AllocMem((Table.FieldCount + 1) * sizeof(CROpType));
Inc(pOp, Table.FieldCount);
pOp^ := crADD;
Dec(pOp, Table.FieldCount);
// Blank out the structure...
FillChar(TableDesc, sizeof(TableDesc), 0);
// Get the database handle from the tables cursor handle...
Check(DbiGetObjFromObj(hDBIObj(Table.Handle), objDATABASE, hDBIObj(hDb)));
// Put the table name in the table descriptor...
StrPCopy(TableDesc.szTblName, Table.TableName);
// Put the table type in the table descriptor...
StrPCopy(TableDesc.szTblType, Props.szTableType);
// Close the table so the restructure can complete...
TableDesc.iFldCount := Table.FieldCount + 1;
Tabledesc.pfldDesc := pFlds;
TableDesc.pecrFldOp := pOp;
Table.Close;
// Call DbiDoRestructure...
try
Check(DbiDoRestructure(hDb, 1, @TableDesc, nil, nil, nil, FALSE));
finally
FreeMem(pFlds);
FreeMem(pOp);
Table.Open;
end;
end;
end.
Topo |
08 - Desabilitar
o botão fechar do formulário
O exemplo abaixo
irá desabilitar o botão fechar do Bloco de Notas do Windows. Antes de testar este
exemplo chame o Bloco de Notas do Windows. Abra um projeto em Delphi e inclua um
componente Button. Inclua o código abaixo no evento OnClick do componente Button.// Evento OnClick do
componente Table
procedure TForm1.Button1Click(Sender: TObject);
var hwndHandle : THANDLE;
hMenuHandle : HMENU;
begin
hwndHandle := FindWindow(nil, 'Sem título - Bloco de Notas');
if (hwndHandle <> 0) then
begin
hMenuHandle := GetSystemMenu(hwndHandle, FALSE);
if (hMenuHandle <> 0) then
DeleteMenu(hMenuHandle, SC_CLOSE,
MF_BYCOMMAND);
end;
end;
Topo |
09 - Mudar o path e o nome dos
arquivos longos para curtos
Para obter este
recurso você irá utilizar a API do Windows chamada GetShortPathName.procedure
TForm1.Button1Click(Sender: TObject);
var Buffer : array [0..255] of char;
begin
GetShortPathName('C:\Arquivos de programas\Borland\Common Files\BDE\
Bde32.hlp',@Buffer,sizeof(Buffer));
Memo1.Lines.Add(Buffer);
end;
Topo |
10 - Desabilitar
um item do componente TRadioGroup
Este exemplo
demonstra como você pode acessar um radio button indivitual do componente TRadioGroup.
Note que o RadioGroup.Controls inicia a partir o 0.procedure TForm1.Button1Click(Sender:
TObject);
begin
TRadioButton(RadioGroup1.Controls[1]). Enabled := False;
end;
Topo |
11 - Acessar a linha ou a
coluna de um StringGrid atravéz do nome
Este exemplo mostra duas funções GetGridColumnByName() e GetGridRowByName() que retornam
a linha e coluna que contenha o valor desejadounit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, Grids;
type
TForm1 = class(TForm)
StringGrid1: TStringGrid;
BitBtn1: TBitBtn;
procedure FormCreate(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
// Evento OnCreate do Form
procedure TForm1.FormCreate(Sender: TObject);
begin
StringGrid1.Rows[1].Strings[0] := 'Esta Linha';
StringGrid1.Cols[1].Strings[0] := 'Esta Coluna';
end;
// Esta função pesquisa a
coluna
function GetGridColumnByName(Grid : TStringGrid;ColName:string):integer;
var i : integer;
begin
for i := 0 to Grid.ColCount - 1 do
if Grid.Rows[0].Strings[i] = ColName then
begin
Result := i;
exit;
end;
Result := -1;
end;
// Esta função pesquisa a
linha
function GetGridRowByName(Grid:TStringGrid;RowName: string):integer;
var i : integer;
begin
for i := 0 to Grid.RowCount - 1 do
if Grid.Cols[0].Strings[i] = RowName then
begin
Result := i;
exit;
end;
Result := -1;
end;
// Evento OnClick do
componente BitBtn
procedure TForm1.BitBtn1Click(Sender: TObject);
var Column,Row : integer;
begin
Column := GetGridColumnByName(StringGrid1, 'Esta Coluna');
if Column = -1 then
ShowMessage('Coluna não encontrada')
else ShowMessage('Coluna encontrada ' + IntToStr(Column));
Row := GetGridRowByName(StringGrid1, 'Esta Linha');
if Row = -1 then
ShowMessage('Linha não encontrada')
else ShowMessage('Linha encontrada ' + IntToStr(Row));
end;
Topo |
12 - Reproduzir um
arquivo MPG
Para testar o exemplo abaixo inclua no seu form um componente MediaPlayer, um componente
Button e um componente Panel.unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ExtCtrls, MPlayer;
type
TForm1 = class(TForm)
Button1: TButton;
MediaPlayer1: TMediaPlayer;
Panel1: TPanel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses mmsystem; // Deve-se declarar a unit mmsystem;
{$R *.DFM}
// Evento OnClick do
componente Button
procedure TForm1.Button1Click(Sender: TObject);
begin
MediaPlayer1.Filename := 'C:\0\teste.mpg';
MediaPlayer1.Open;
MediaPlayer1.Display := Panel1;
MediaPlayer1.DisplayRect := Panel1.ClientRect;
MediaPlayer1.Play;
end;
Topo |
13 - Alterar a font de
um Hint
Para testar este
exemplo inclua no seu form alguns componentes. Nestes componentes coloque informações na
propriedade Hint de cada componente e altere a propriedade ShowHint para True.unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Edit1: TEdit;
Edit2: TEdit;
Edit3: TEdit;
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure MyShowHint(var HintStr: string;
var CanShow: Boolean;
var HintInfo: THintInfo);
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
// Função que irá alterar a
fonte do Hint
procedure TForm1.MyShowHint(var HintStr: string;
var CanShow: Boolean;
HintInfo: THintInfo);
i : integer;
begin
for i := 0 to Application.ComponentCount - 1 do
if Application.Components[i] is THintWindow then
with THintWindow(Application.Components[i]).Canvas do
begin
Font.Name := 'Arial';
Font.Size := 18;
Font.Style := [fsBold];
HintInfo.HintColor := clWhite;
end;
end;
// Evento OnCreate do Form
procedure TForm1.FormCreate(Sender: TObject);
begin
// Ativa a função que irá alterar o formato do Hint
Application.OnShowHint := MyShowHint;
end;
Topo |
14 - Mostrar o Hint
independentemente para cada coluna do StringGrid
Para testar o
exemplo abaixo inclua no seu form um componente StringGridunit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Grids;
type
TForm1 = class(TForm)
StringGrid1: TStringGrid;
procedure FormCreate(Sender: TObject);
procedure StringGrid1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
private
{ Private declarations }
public
{ Public declarations }
Col,Row : integer; // Declarar esta variável
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
// Evento OnCreate do Form
procedure TForm1.FormCreate(Sender: TObject);
begin
StringGrid1.Hint := '0 0';
StringGrid1.ShowHint := True;
end;
// Evento OnMouseMove do
componente StringGrid
procedure TForm1.StringGrid1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
var r,c : integer;
begin
StringGrid1.MouseToCell(X, Y, C, R);
if ((Row <> r) or (Col <> c)) then
begin
Row := r; Col := c;
Application.CancelHint;
StringGrid1.Hint := 'Linha:
'+IntToStr(r)+#32+'Coluna: '+IntToStr(c);
end;
end;
Topo |
15 - Retornar
a cor de um pixel de uma imagem
Para testar o
exemplo inclua em um form um componente Image e inclua neste componente Image uma imagem
qualquer. Inclua o código abaixo no evento OnMouseMove.procedure TForm1.Image1MouseMove(Sender:
TObject; Shift: TShiftState; X,
Y: Integer);
begin
// Retornar a cor
Caption := ColorToString(Image1.Canvas.Pixels[X,Y]);
// Retornar o número da cor
Caption := Caption+' - '+IntToStr(ColorToRGB(Image1.Canvas.Pixels[X,Y]));
end;
Topo |
16 - Chamar um site
pelo Delphi
Para testar o
exemplo abaixo inclua no seu form um componente Button e inclua o código abaixo no evento
OnClick do componente Button.implementation
uses UrlMon;
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
HlinkNavigateString(nil,http://www.geocities.com);
end;
Topo |
17 - Mudar o
papel de parede do Windows
Para testar o exemplo abaixo inclua no seu form um componente Button e no evento OnClick o
código abaixo:procedure TForm1.Button1Click(Sender: TObject);
begin
SystemParametersInfo(SPI_SETDESKWALLPAPER,0,
PChar(C:\windows\Arenito.bmp),SPIF_SENDWININICHANGE);
end;
Topo |
18 - Verificar o
idioma do Windows
O exemplo abaixo mostra como chamar a calculadora do Windows independente do idioma do
Windows, por exemplo, português ou inglês.procedure TForm1.SpeedButton1Click(Sender:
TObject);
var TheWindow: HWND;
Lingua: array[0..255] of char;
begin
VerLanguageName(GetSystemDefaultLangID, Lingua, 255);
{ Verifica se o Windows é Português ou Brasileiro }
if Lingua <> Português (Brasileiro) then
TheWindow:=FindWindow(nil,Calculadora)
else
if Lingua <> English (United States) then
TheWindow:=FindWindow(nil,Calculator)
{ Procura a janela da
calculadora }
if TheWindow <> 0 then
begin
// Chama calculadora se já estiver carregada
SetForegroundWindow(TheWindow);
ShowWindow(TheWindow, SW_RESTORE);
end
else
// Carrega calculadora se estiver fechada
ShellExecute(Handle, Open, Calc.exe, nil,
c:\windows, sw_show);
end;
end.
Topo |
19 - Adicionar ou remover a senha de
uma tabela Paradox
Para testar este exemplo inclua
no seu form dois componentes TButton e um componente TEdit.unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Grids, DBGrids, Db, DBTables, BDE;
type
TForm1 = class(TForm)
Button1: TButton;
Table1: TTable;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
Edit1: TEdit;
Label1: TLabel;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
procedure AddMasterPassword(Table: TTable; pswd: string);
procedure RemoveMasterPassword(Table: TTable);
var
Form1: TForm1;
implementation
{$R *.DFM}
// Adiciona a senha ao Banco
de Dados
procedure TForm1.Button1Click(Sender: TObject);
begin
Table1.Close;
Table1.Exclusive := True;
Table1.Open;
AddMasterPassword(Table1,Edit1.Text);
Table1.Close;
Table1.Exclusive := False;
Table1.Open;
end;
// Remove a senha ao Banco de
Dados
procedure TForm1.Button2Click(Sender: TObject);
begin
Table1.Close;
Table1.Exclusive := True;
Table1.Open;
RemoveMasterPassword(Table1);
Table1.Close;
Table1.Exclusive := False;
Table1.Open;
end;
// Esta função adiciona a
senha ao banco de dados
procedure
AddMasterPassword(Table: TTable; pswd: string);
const RESTRUCTURE_TRUE = WordBool(1);
var TblDesc: CRTblDesc;
hDb: hDBIDb;
begin
if not Table.Active or not Table.Exclusive then
raise EDatabaseError.Create(Table must be opened in
exclusive +
mode to add passwords);
FillChar(TblDesc, SizeOf(CRTblDesc), #0);
with TblDesc do
begin
StrPCopy(szTblName, Table.TableName);
StrCopy(szTblType, szPARADOX);
StrPCopy(szPassword, pswd);
bProtected := RESTRUCTURE_TRUE;
end;
Check(DbiGetObjFromObj(hDBIObj(Table.Handle), objDATABASE, hDBIObj(hDb)));
Table.Close;
Check(DbiDoRestructure(hDb, 1, @TblDesc, nil, nil, nil, False));
Session.AddPassword(pswd);
Table.Open;
end;
// Esta função remove a senha ao banco de dados
procedure RemoveMasterPassword(Table: TTable);
const RESTRUCTURE_FALSE = WordBool(0);
var TblDesc: CRTblDesc;
hDb: hDBIDb;
begin
if (Table.Active = False) or (Table.Exclusive = False) then
raise EDatabaseError.Create(Table must be opened in
exclusive mode to add passwords);
FillChar(TblDesc, SizeOf(CRTblDesc), 0);
with TblDesc do
begin
StrPCopy(szTblName, Table.TableName);
StrCopy(szTblType, szPARADOX);
bProtected := RESTRUCTURE_FALSE;
end;
Check(DbiGetObjFromObj(hDBIObj(Table.Handle), objDATABASE, hDBIObj(hDb)));
Table.Close;
Check(DbiDoRestructure(hDb, 1, @TblDesc, nil, nil, nil, FALSE));
Table.Open;
end;
end.
Topo |
20 - Extensões das
tabelas Paradox
.DB - Tabela Paradox
.FAM - Lista de arquivos relacionados
.LCK - Arquivo de Lock
.MB - Campos Blobs
.PX - Indice Primário
.TV - Guarda as configurações da tabela (não usado pelo BDE)
.VAL - Valid checks e integridade referencial.
.Xnn - índice secundário de campo único
.Ynn - índice secundário de campo único.
.XGn - índice secundário composto
.YGn - índice secundário compostoTopo |
21 - Arquivos AVI e WAV
O exemplo abaixo demonstra como
gravar um arquivo .AVI ou .WAV dentro de um arquivo paradox. Mostra também como
reproduzir estes arquivos.
Para que o código abaixo funcione inclua em um Form 02 componentes Button, 01 componente
Panel, 01 componente DBGrid, 01 componente Table, 01 componente DataSource e 01 componente
OpenDialog.Crie um arquivo Paradox com a seguinte estrutura:
Nome |
Tipo |
Tamanho |
Codigo |
+ |
|
Nome |
A |
100 |
Avi |
B |
|
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Db, DBTables, ExtCtrls, MPlayer, DBCtrls, Grids, DBGrids;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Table1: TTable;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
Panel1: TPanel;
OpenDialog1: TOpenDialog;
Table1Codigo: TAutoIncField;
Table1Nome: TStringField;
Table1Avi: TBlobField;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
{ Public declarations }
end;
var Form1: TForm1;
FileName : string;
MediaPlayer1 : TMediaPlayer;
implementation
{$R *.DFM}
{Esta função cria um arquivo
temporário para o sistema}
function GetTemporaryFileName
: string;
{$IFNDEF WIN32}
const MAX_PATH = 144;
{$ENDIF}
var
{$IFDEF WIN32}
lpPathBuffer : PChar;
{$ENDIF}
lpbuffer : PChar;
begin
{Get the file name buffer}
GetMem(lpBuffer, MAX_PATH);
{$IFDEF WIN32}
{Get the temp path buffer}
GetMem(lpPathBuffer, MAX_PATH); {Get the temp path}
GetTempPath(MAX_PATH, lpPathBuffer); {Get the temp file name}
GetTempFileName(lpPathBuffer,tmp,0,lpBuffer);
FreeMem(lpPathBuffer, MAX_PATH);
{$ELSE} {Get the temp file name}
GetTempFileName(GetTempDrive(C),tmp,0,lpBuffer);
{$ENDIF} {Create a pascal string containg}
{the temp file name and return it}
result := StrPas(lpBuffer);
{Free the file name buffer}
FreeMem(lpBuffer, MAX_PATH);
end;
{Grava AVI ou Wav no arquivo
PARADOX}
procedure
TForm1.Button1Click(Sender: TObject);
var FileStream: TFileStream; {para ler o arquivo avi}
BlobStream: TBlobStream; {para salvar no campo blob}
begin
Application.ProcessMessages;
Button1.Enabled := false;
Button2.Enabled := false;
if OpenDialog1.Execute then
FileStream :=
TFileStream.Create(OpenDialog1.FileName,fmOpenRead);
Table1.Append;
Table1Nome.Value := OpenDialog1.FileName;
BlobStream := TBlobStream.Create(Table1AVI, bmReadWrite);
BlobStream.Seek(0, soFromBeginning);
BlobStream.Truncate;
BlobStream.CopyFrom(FileStream, FileStream.Size);
FileStream.Free;
BlobStream.Free;
Table1.Post;
Button1.Enabled := true;
Button2.Enabled := true;
end;
{Reproduz o que está gravado
no campo Blob}
procedure
TForm1.Button2Click(Sender: TObject);
var FileStream: TFileStream; {a temp file}
BlobStream: TBlobStream; {the AVI Blob}
begin
BlobStream := TBlobStream.Create(Table1AVI, bmRead);
if BlobStream.Size = 0 then
begin
BlobStream.Free;
Exit;
end;
MediaPlayer1.Close; {Reset the file name}
MediaPlayer1.FileName := ; {Refresh the play window}
MediaPlayer1.Display := Panel1;
Panel1.Refresh;
if FileName <> then
DeleteFile(FileName); {Get a temp file name}
FileName := GetTemporaryFileName; {Create a temp file stream}
FileStream := TFileStream.Create(FileName,fmCreate or fmOpenWrite);
FileStream.CopyFrom(BlobStream, BlobStream.Size); {Free the streams}
FileStream.Free; BlobStream.Free;
MediaPlayer1.FileName := filename;
MediaPlayer1.DeviceType := dtAviVideo;
MediaPlayer1.Open;
MediaPlayer1.Play;
end;
// Evento OnDestroy do Form
procedure
TForm1.FormDestroy(Sender: TObject);
begin
MediaPlayer1.Close;
MediaPlayer1.FileName := ;
if FileName <> then
DeleteFile(FileName);
end;
// Evento OnShow do Form
procedure TForm1.FormShow(Sender: TObject);
begin
MediaPlayer1 := TMediaPlayer.Create(self);
with MediaPlayer1 do
begin
Parent := self ;
Visible := False;
end;
Table1.Open;
end;
// Evento OnClose do Form
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Table1.Close;
end;
end.
Topo |
22 - Executando um programa DOS e
fechando em seguida
Quando você executa um programa
DOS no Windows95, sua janela permanece aberta até ser fechada pelo usuário.
Para executar um programa DOS que fecha sua janela após a execução, deve ser
especificado "command.com /c programa" na linha de comando. Usando a função da
API WinExec para executar um programa chamado progdos.exe, a chamada deve ser:
WinExec('command.com /c progdos.exe',sw_ShowNormal);
Obs. Se o programa deve ser executado sem que seja visualizado pelo usuário, o segundo
parâmetro deve ser sw_Hide. Deve ser especificada a extensão .com senão o programa não
será executado.Topo |
23 - Copiar registros
de uma tabela para outra incluindo valores NULL
Procedure
TtableCopiaRegistro(Origem, Destino: Ttable);
begin
with TabelaOrig do
begin
{Inicia um contador para os campos da
TabelaOrig}
for i := 0 to FieldCount -1 do
{Este if verifica se o campo da TabelaOrig é NULL, se for,
atribui seu valor ao campo da TabelaDest}
if not Fields[i].IsNull then
TabelaDest.Fields[i].Assign(Fields[i]);
end; {end with}
end;
Este exemplo funcionará com todos tipos de campos se você tiver acabado
de criar a TabelaDest.
Para criar um dado valor NULL : Fields[i].ClearTopo |
24 - Criar uma tabela Paradox com um
campo Increment
Abaixo um exemplo de um form com um
botão. Clicando no botão será criada
uma tabela com um campo autoincrement usando DbiCreateTable (função
chamada da API do BDE)
unit Autoinc;
interface
uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
Forms, Dialogs, DBTables, DB, ExtCtrls, DBCtrls, Grids, DBGrids, StdCtrls,
DbiTypes, DbiErrs, DBIProcs;
const
szTblName = 'CR8PXTBL'; { Nome da tabela a ser criada. }
szTblType = szPARADOX; { tipo da tabela a ser criada. }
{ Descrição do campo usada durante a criação da tabela}
const
fldDes: array[0..1] of FLDDesc = (( { Field 1 - AUTOINC }
iFldNum: 1; { Field Number }
szName: 'AUTOINC'; { Field Name }
iFldType: fldINT32; { Field Type }
iSubType: fldstAUTOINC; { Field Subtype }
iUnits1: 0; { Field Size }
iUnits2: 0; { Decimal places (0) }
iOffset: 0; { Offset in record (0) }
iLen: 0; { Length in Bytes (0) }
iNullOffset: 0; { For Null Bits (0) }
efldvVchk: fldvNOCHECKS; { Validiy checks (0) }
efldrRights: fldrREADWRITE { Rights } ),
( { Field 2 - ALPHA }
iFldNum: 2; szName: 'ALPHA';
iFldType: fldZSTRING; iSubType: fldUNKNOWN;
iUnits1: 10; iUnits2: 0;
iOffset: 0; iLen: 0;
iNullOffset: 0; efldvVchk: fldvNOCHECKS;
efldrRights: fldrREADWRITE
) );
type
TForm1 = class(TForm)
Button1: TButton;
Database1: TDatabase;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
Var TblDesc: CRTblDesc;
uNumFields: Integer;
Rslt : DbiResult;
ErrorString : Array[0..dbiMaxMsgLen] of Char;
begin
FillChar(TblDesc, sizeof(CRTblDesc), #0);
lStrCpy(TblDesc.szTblName, szTblName);
lStrCpy(TblDesc.szTblType, szTblType);
uNumFields := trunc(sizeof(fldDes) / sizeof (fldDes[0]));
TblDesc.iFldCount := uNumFields;
TblDesc.pfldDesc := @fldDes;
Rslt := DbiCreateTable(Database1.Handle, TRUE, TblDesc);
If Rslt <> dbiErr_None then
begin
DbiGetErrorString(Rslt, ErrorString);
MessageDlg(StrPas(ErrorString),mtWarning,[mbOk],0);
end;
end;
end.
Notas:
Se você usa o campo autoincrement com parte da chave primária
(a razão mais comun de se usar esse tipo de campo), e, se você usar
esse campo autoincrement como chave estrangeira de outra tabela, você
pode ter problemas! Se a tabela com autoincrement for recronstruída
(REBUILD), por qualquer motivo, ela criará uma nova contagem. Isso
causará perda de relacionamento com outra tabela! Por essa razão, você
deve manter uma contagem manual de numero seqüêncial para fazer parte
de uma chave primária. Isso tira o maior benefício do campo auto-
increment fazendo com que ele perca seu maior uso prático.
Topo |
25 - Remover
fisicamente os registros apagados
Para compactar (remover
fisicamente todos registros apagados) de uma tabela Paradox deve-se utilizar o seguinte
código:procedure ParadoxPack(Table : TTable);
var TBDesc : CRTblDesc;
HDb: hDbiDb;
TablePath: array[0..dbiMaxPathLen] of char;
Begin
FillChar(TBDesc,Sizeof(TBDesc),0);
With TBDesc do begin
StrPCopy(szTblName,Table.TableName);
StrPCopy(szTblType,szParadox);
BPack := True;
End;
HDb := nil;
Check(DbiGetDirectory(Table.DBHandle, True, TablePath));
Table.Close;
Check(DbiOpenDatabase(nil, 'STANDARD', dbiReadWrite,
DbiOpenExcl,nil,0, nil, nil, hDb));
Check(DbiSetDirectory(hDb, TablePath));
Check(DBIDoRestructure(hDb,1,@TBDesc,nil,nil,nil,False));
Table.Open;
End;
Topo |
26 - Verificar
validação de CGC e CPF
InterfaceFunction cpf(num: string): boolean;
function cgc(num: string): boolean;
implementation
uses SysUtils;
function cpf(num: string):
boolean;
var n1,n2,n3,n4,n5,n6,n7,n8,n9,d1,d2: integer;
digitado, calculado: string;
begin
n1:=StrToInt(num[1]);
n2:=StrToInt(num[2]);
n3:=StrToInt(num[3]);
n4:=StrToInt(num[4]);
n5:=StrToInt(num[5]);
n6:=StrToInt(num[6]);
n7:=StrToInt(num[7]);
n8:=StrToInt(num[8]);
n9:=StrToInt(num[9]);
d1:=n9*2+n8*3+n7*4+n6*5+n5*6+n4*7+n3*8+n2*9+n1*10;
d1:=11-(d1 mod 11);
if d1 >= 10 then
d1:=0;
d2:=d1*2+n9*3+n8*4+n7*5+n6*6+n5*7+n4*8+n3*9+n2*10+n1*11;
d2:=11-(d2 mod 11);
if d2 >= 10 then
d2:=0;
calculado:=inttostr(d1)+inttostr(d2);
digitado:=num[10]+num[11];
if calculado = digitado then
cpf:=true
else cpf:=false;
end;
function cgc(num: string):
boolean;
var n1,n2,n3,n4,n5,n6,n7,n8,n9,n10,n11,n12,d1,d2: integer;
digitado, calculado: string;
begin
n1:=StrToInt(num[1]);
n2:=StrToInt(num[2]);
n3:=StrToInt(num[3]);
n4:=StrToInt(num[4]);
n5:=StrToInt(num[5]);
n6:=StrToInt(num[6]);
n7:=StrToInt(num[7]);
n8:=StrToInt(num[8]);
n9:=StrToInt(num[9]);
n10:=StrToInt(num[10]);
n11:=StrToInt(num[11]);
n12:=StrToInt(num[12]);
d1:=n12*2+n11*3+n10*4+n9*5+n8*6+n7*7+n6*8+n5*9+n4*2+n3*3+n2*4+n1*5;
d1:=11-(d1 mod 11);
if d1 >= 10 then
d1:=0;
d2:=d1*2+n12*3+n11*4+n10*5+n9*6+n8*7+n7*8+n6*9+n5*2+n4*3+n3*4+n2*5+n1*6;
d2:=11-(d2 mod 11);
if d2 >= 10 then
d2:=0;
calculado:=inttostr(d1)+inttostr(d2);
digitado:=num[13]+num[14];
if calculado = digitado then
cgc:=true
else cgc:=false;
end;
end.
Topo |
28 - Colocar
uma Imagem dentro de um ComboBox
-Ajuste a
propriedade Style do ComboBox para csOwnerDrawVariable.
var Form1: TForm1;
Bmp1, Bmp2, Bmp3: TBitmap;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
Bmp1:=TBitmap.Create;
Bmp.Loadfromfile('c:\chip16.bmp');
Bmp1:=TBitmap.Create;
Bmp.Loadfromfile('c:\zoom.bmp');
Bmp1:=TBitmap.Create;
Bmp.Loadfromfile('c:\disk.bmp');
ComboBox1.Items.AddObject('Chip',Bmp1);
ComboBox1.Items.AddObject('Zoom',Bmp2);
ComboBox1.Items.AddObject('Disk',Bmp3);
end;
procedure TForm1.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOWnerDrawState);
var Bitmap: TBitmap;
Offset: Integer;
begin
with (Control as TComboBox).Canvas do
begin
FillRect(Rect);
Bitmap:= TBitmap(ComboBox1.Items.Objects[index]);
if Bitmap nil then
begin
BrushCopy(Bounds(Rect.Left + 2, Rect.Top + 2, Bitmap.Width,
Bitmap.Height), Bitmap,
Bounds(0, 0, Bitmap.Width,
Bitmap.Height),
clRed);
Offset: Bitmap.width + 8;
end;
TextOut(Rect.Left + Offset, Rect.Top,
ComboBox1.Items[index]);
end;
end;
procedure TForm1.ComboBox1MeasureItem(Control: TWinControl; Index: Integer;
var Height: Integer);
begin
Height:=20;
end; Topo |
29 - Conectar em
uma unidade de rede
procedure
TForm1.Button1Click(Sender: TObject);
var NRW: TNetResource;
begin
with NRW do
begin
dwType := RESOURCETYPE_ANY;
lpLocalName := 'g:';
lpRemoteName := '\\servidor\hdc';
lpProvider := '';
end;
WNetAddConnection2(NRW, 'MyPassword', 'MyUserName',
CONNECT_UPDATE_PROFILE);
end; Topo |
30 - Criar
um formulário de Apresentação
Para você criar um pequeno Form de
apresentação enquanto seu programa é carregado ou enquanto sua aplicação gera
indices, etc.
Crie seu Form de Apresentação e depois no menu View/Project Source, inclua o seguinte
código:
program ViewSchooll;
uses
Forms,
Windows,
Apresentacao in 'Apresentacao.pas' {FrmApresentacao},
FmPrincipal in 'FmPrincipal.pas' {FrmPrincipal};
{$R *.RES}
begin
FrmApresentacao := TFrmApresentacao.Create(Application);
FrmApresentacao.Show;
FrmApresentacao.Update;
sleep(3000);
FrmApresentacao.Free;
Application.Initialize;
Application.CreateForm(TFrmSistema, FrmSistema);
Application.Run;
end. Topo |
31 - Inserir
automaticamente no sistema a senha de uma tabela Paradox
Entre em View/Project Source do
Delphi. Não esqueça de adicionar a unit DBTables dentro do uses
program ViewSchooll;
uses
Forms,
Windows,
DBTables,
FmPrincipal in 'FmPrincipal.pas' {FrmPrincipal};
{$R *.RES}
begin
Session.AddPassword('90028865');
Application.Initialize;
Application.CreateForm(TFrmSistema, FrmSistema);
Application.Run;
end. Topo |
32 - Como
saber se o aplicativo esta aberto
Entre em View/Project Source do
Delphi.
program ViewSchooll;
uses
Forms,
Windows,
FmPrincipal in 'FmPrincipal.pas' {FrmPrincipal};
{$R *.RES}
begin
if HPrevInst = 0 then
begin
Session.AddPassword('90028865');
Application.Initialize;
Application.CreateForm(TFrmSistema, FrmSistema);
Application.Run;
end
else ShowMessage('O Aplicativo já esta aberto');
end. Topo |
34 - Colocar tamanho minimo e maximo
para um formulário
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TForm1 = class(TForm)
private
{ Private declarations }
procedure WMGetMinMaxInfo(var MSG: TMessage); message WM_GetMinMaxInfo;
public
{ Public declarations }
end;
var Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.WMGetMinMaxInfo(var MSG: TMessage);
begin
inherited;
with PMinMaxInfo(MSG.lparam)^ do
begin
ptMinTRackSize.X := 300;
ptMinTRackSize.Y := 150;
ptMaxTRackSize.X := 350;
ptMaxTRackSize.Y := 250;
end;
end;
end. Topo |
35 - Verificar
se tem disquete no Drive
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
function NaoTemDisco(const drive : char): boolean;
private
{ Private declarations }
public
{ Public declarations }
end;
var Form1: TForm1;
implementation
{$R *.DFM}
function TForm1.NaoTemDisco(const drive : char): boolean;
var DriveNumero : byte;
EMode : word;
begin
result := false;
DriveNumero := ord(Drive);
if DriveNumero >= ord('a') then
dec(DriveNumero,$20);
EMode := SetErrorMode(SEM_FAILCRITICALERRORS);
try
if DiskSize(DriveNumero-$40) = -1 then
Result := true
else messagebeep(0);
finally
SetErrorMode(EMode);
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if NaoTemDisco('a') then
ShowMessage('Não tem Disco no Drive A:')
else ShowMessage('Tem disco No drive A:');
end;
end. Topo |
36 - Jogar uma imagem direto para um
campo da tabela
procedure
TForm1.Button1Click(Sender: TObject);
var BMP: TBitMap;
begin
BMP := TBitMap.Create;
if OpenPictureDialog1.Execute then
begin
if Table1.State in [dsInsert, dsEdit] then
begin
BMP.LoadFromFile(OpenPictureDialog1.FileName);
Table1Graphic.Assign(
BMP );
end;
end;
end; Topo |
37 - Incluir
evento OnClick no DBGrid
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Grids, DBGrids, DB, DBTables;
type
thack = class(tcontrol);
TForm1 = class(TForm)
Table1: TTable;
DataSource1: TDataSource;
DBGrid1: TDBGrid;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
THack(dbgrid1).controlstyle := THack(dbgrid1).controlstyle +
[csClickEvents];
THack(dbgrid1).OnClick := Form1.OnClick;
end;
procedure TForm1.FormClick(Sender: TObject);
begin
ShowMessage(Teste);
application.processmessages;
end;
end. Topo |
38 - Como
alterar a data e a hora do Sistema
procedure
TForm1.Button1Click(Sender: TObject);
begin
SetNewTime(1998,2,10,18,07);
end;
function SetNewTime(Ano, Mes, Dia, hour, minutes: word): Boolean;
var data:TSystemTime;
begin
GetLocalTime(data);
data.wYear := Ano;
data.wMonth := Mes;
data.wDay := Dia;
data.wHour := hour;
data.wMinute := minutes;
if not SetLocalTime(Data) then
Result := False
else Result := True;
end; Topo |
39 - Retornar a
coluna ativa do DBGrid
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, DBTables, Grids, DBGrids;
type
TForm1 = class(TForm)
DBGrid1: TDBGrid;
Table1: TTable;
DataSource1: TDataSource;
procedure DBGrid1ColEnter(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.DBGrid1ColEnter(Sender: TObject);
begin
Caption := DBGrid1.SelectedField.FieldName;
end; Topo |
40 - Colocar
um ComboBox dentro de um StringGrid
Inclua no
seu Form um componente ComboBox e um componente StringGrid.
type
TForm1 = class(TForm)
StringGrid1: TStringGrid;
ComboBox1: TComboBox;
procedure FormCreate(Sender: TObject);
procedure ComboBox1Change(Sender: TObject);
procedure ComboBox1Exit(Sender: TObject);
procedure StringGrid1SelectCell
(Sender: TObject; Col, Row: Integer;
var CanSelect: Boolean);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
// Evento OnCreate do Form
procedure TForm1.FormCreate(Sender: TObject);
begin
{ Ajusta a altura do ComboBox com a altura da linha do StringGrid}
StringGrid1.DefaultRowHeight := ComboBox1.Height;
{Esconde o ComboBox}
ComboBox1.Visible := False;
end;
// Evento OnChange do componente ComboBox
procedure TForm1.ComboBox1Change(Sender: TObject);
begin
StringGrid1.Cells[StringGrid1.Col,StringGrid1.Row] :=
ComboBox1.Items[ComboBox1.ItemIndex];
ComboBox1.Visible := False;
StringGrid1.SetFocus;
end;
// Evento OnExit do componente ComboBox
procedure TForm1.ComboBox1Exit(Sender: TObject);
begin
StringGrid1.Cells[StringGrid1.Col,StringGrid1.Row] :=
ComboBox1.Items[ComboBox1.ItemIndex];
ComboBox1.Visible := False;
StringGrid1.SetFocus;
end;
// Evento OnSelectCell do componente StringGrid
procedure TForm1.StringGrid1SelectCell(Sender: TObject; Col, Row: Integer;
var CanSelect: Boolean);
var R: TRect;
begin
if ((Col = 3) AND (Row <> 0)) then
begin
R := StringGrid1.CellRect(Col, Row);
R.Left := R.Left + StringGrid1.Left;
R.Right := R.Right + StringGrid1.Left;
R.Top := R.Top + StringGrid1.Top;
R.Bottom := R.Bottom + StringGrid1.Top;
ComboBox1.Left := R.Left + 1;
ComboBox1.Top := R.Top + 1;
ComboBox1.Width := (R.Right + 1) - R.Left;
ComboBox1.Height := (R.Bottom + 1) - R.Top;
ComboBox1.Visible := True;
ComboBox1.SetFocus;
end;
CanSelect := True;
end; Topo |
41 - Pegar
informações do Ambiente DOS
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Grids;
type
TForm1 = class(TForm)
Button1: TButton;
StringGrid1: TStringGrid;
ListBox1: TListBox;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
var Env : PChar;
i : Integer;
S : String;
PosEq : Integer;
begin
Env := GetEnvironmentStrings;
With ListBox1,StringGrid1 do
begin
While Env^ <> #0 do
begin
Items.Add(StrPas(Env));
Inc(Env,StrLen(Env)+1);
end;
RowCount := Items.Count;
for i := 0 to Pred(Items.Count) do
begin
PosEq := Pos('=',Items[i]);
Cells[0,i] :=
Copy(Items[i],1,PosEq-1);
Cells[1,i] :=
Copy(Items[i],PosEq+1,Length(Items[i]));
end;
end;
end;
end. Topo |
42 - ShowMessage
com quebra de linhas
procedure
TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(Primeira Linha+#13+Segunda
Linha+#13+Terceira Linha);
end;
ATENÇÃO. A quebra foi possível através do codigo #13.
Topo |
43 - Mostrar as fontes TrueTypes
instaladas no Windows
Para testar
o exemplo abaixo inclua em seu formulário um componente ListBox, um componente Label e um
componente
ListBox.
// Evento OnClick do componente LisBox
procedure TForm1.ListBox1Click(Sender: TObject);
begin
{Atribui a propriedade Caption do componente Label o nome da fonte
selecionada apenas para visualização}
Label1.Caption := ListBox1.Items[ListBox1.ItemIndex];
{Atribui ao componente Label1 na propriedade Name da propriedade Font o
nome da fonte selecionada para que o componente Label para utilizar a
mesma fonte }
Label1.Font.Name := ListBox1.Items[ListBox1.ItemIndex];
end;
// Evento OnClick do componente Button.
procedure TForm1.Button1Click(Sender: TObject);
begin
{Carrega as fontes instaladas no Windows para o componente ListBox}
ListBox1.Items := Screen.Fonts;
end; Topo |
44 - Configuração
do DBE para Rede
Para o seu
aplicativo feito em Delphi rodar em rede, você deve instalar o BDE em todas as
estações. No BDE de cada estação, você deve colocar no parâmetro NET DIR do drive
PARADOX o local onde estão as bases de dados e na PATH do Alias especificar o caminho das
base de dados. Mas muita atenção, todas as estações devem estar com a mesma
configuração do BDE. Veja o exemplo abaixo para configuração do parâmetro NET
DIR do drive PARADOX e o PATH do Alias.
Estação n.1
NET DIR F:\
Path do Alias F:\DIRETORIO
Estação n.2
NET DIR F:\
Path do Alias F:\DIRETORIO
Estação n.3
NET DIR F:\
Path do Alias F:\DIRETORIO
Não é aconselhável que os aplicativos feitos em Delphi 1, sejam executados no servidor
da base de dados, pois o PARADOX apresenta problemas de corrupção de arquivos e índices
neste caso. É aconselhável que no servidor você coloque somente as bases de dados. Mas
caso você tenha necessidade de utilizar o servidor você pode utilizar uma solução
alternativa para o problema do PARADOX, esta solução esta sendo satisfatória na maioria
dos casos. Digamos que a letra do drive de rede que você vai acessar o servidor, seja a
letra F:, então, faça o seguinte: Coloque a linha abaixo no arquivo
AUTOEXEC.BAT, do servidor.
SUBST F: C:
Configure o BDE do servidor para que ele acesse o drive F:
Esta linha deverá ser colocada apenas no servidor, com isso você passa a ter em seu
servidor, um drive virtual para acessar o
drive C:, evitando o problema do PARADOX.
No Delphi 2 e Delphi 3, você deve utilizar um instalador de programas. No CD do Delphi 2
e Delphi 3 existe um instalador
chamado InstallShield para fazer a instalação e configuração do aplicativo e do BDE.
Veja abaixo os exemplos da configuração do BDE p/ Delphi 2 e 3:
Servidor Estação 1
NET DIR \\SERVIDOR\C NET DIR \\SERVIDOR\C
PATH DO ALIAS \\SERVIDOR\C\DIRETORIO PATH DO ALIAS \\SERVIDOR\C\DIRETORIO
LOCAL SHARE TRUE LOCAL SHARE FALSE
Estação 2 Estação 3
NET DIR \\SERVIDOR\C NET DIR \\SERVIDOR\C
PATH DO ALIAS \\SERVIDOR\C\DIRETORIO PATH DO ALIAS \\SERVIDOR\C\DIRETORIO
LOCAL SHARE FALSE LOCAL SHARE FALSE
DICA: O executável pode ser colocado em cada máquina da rede, diminuindo assim o
tráfego de rede. Topo |
45 - Retorna o usuário que esta com
a tabela exclusiva
procedure
TForm1.BitBtn1Click(Sender: TObject);
begin
try
Table1.Close;
Table1.Exclusive := True;
Table1.Open;
except on E:EDBEngineError do
if E.Errors[0].ErrorCode = 10243 then
begin
ShowMessage(Mensagem de
erro+E.Errors[0].Message );
ShowMessage( Arquivo com
erro+E.Errors[1].Message );
ShowMessage( Nome do
usuario+ E.Errors[2].Message );
end;
end;
end; Topo |
46 - Retornar o usuario que esta
editando o registro
procedure
TForm1.BitBtn1Click(Sender: TObject);
begin
try
Table1.Edit;
except on E:EDBEngineError do
if E.Errors[0].ErrorCode = 10241 then
begin
ShowMessage(Mensagem de
erro+E.Errors[0].Message );
ShowMessage( Arquivo com
erro+E.Errors[1].Message );
ShowMessage( Nome do usuario+
E.Errors[2].Message );
end;
end;
end;Topo |
47 - Mostrar o Hint em
um Panel
procedure
TForm1.FormCreate(Sender: TObject);
begin
Application.OnHint := DisplayHint;
end;
procedure TForm1.DisplayHint(Sender: TObject);
begin
Panel1.Caption := Application.Hint;
end;
Obs. Não é necessário Atribuir True para o ShowHint para os componentes
Topo |
48 - Imprimir em impressora matricial
em modo caracter
procedure
TForm1.Button1Click(Sender: TObject);
var Arquivo : TextFile;
begin
AssignFile(Arquivo,LPT1');
Rewrite(Arquivo);
Writeln(Arquivo,Teste de impressao - Linha 0');
Writeln(Arquivo,Teste de impressao - Linha 1');
Writeln(Arquivo,#27#15+Teste de Impressão - Linha 2');
Writeln(Arquivo,Teste de impressao - Linha 3');
Writeln(Arquivo,#27#18+Teste de Impressão - Linha 4');
Writeln(Arquivo,Teste de impressao - Linha 5');
Writeln(Arquivo,#12); // Ejeta a página
CloseFile(Arquivo);
end; Topo |
49 - Hint com quebra de
linhas
Para incluir mais
de uma linha no Hint você deve utilizar o evento OnMouseMove de cada componente.
Veja abaixo como ficará o código em um Edit por exemplo.
procedure TForm1.Edit1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
Edit1.hint := Linha 1+#13+Linha 2+#13+Linha
3+#13+Linha 4;
end;
Obs. Não esquecer de mudar para TRUE o evento ShowHint. Topo |
50 - Compactando tabelas
Para compactar
(remover fisicamente todos registros apagados) de uma tabela Paradox deve-se utilizar o
seguinte código:procedure
ParadoxPack(Table : TTable);
var TBDesc : CRTblDesc;
hDb: hDbiDb;
TablePath: array[0..dbiMaxPathLen] of char;
begin
FillChar(TBDesc,Sizeof(TBDesc),0);
with TBDesc do
begin
StrPCopy(szTblName,Table.TableName);
StrPCopy(szTblType,szParadox);
bPack := True;
end;
hDb := nil;
Check(DbiGetDirectory(Table.DBHandle, True, TablePath));
Table.Close;
Check(DbiOpenDatabase(nil, 'STANDARD', dbiReadWrite,
dbiOpenExcl,nil,0, nil, nil, hDb));
Check(DbiSetDirectory(hDb, TablePath));
Check(DBIDoRestructure(hDb,1,@TBDesc,nil,nil,nil,False));
Table.Open;
end;
Topo |
51 - Gravar
imagem JPG em tabela Paradox
Procedure
Grava_Imagem_JPEG(Tabela:TTable; Campo:TBlobField;
Foto:TImage; Dialog:TOpenPictureDialog);
var BS:TBlobStream;
MinhaImagem:TJPEGImage;
Begin
Dialog.InitialDir := 'c:\temp';
Dialog.Execute;
if Dialog.FileName <> '' Then
Begin
if not (Tabela.State in [dsEdit, dsInsert]) Then
Tabela.Edit;
BS := TBlobStream.Create((Campo as TBlobField),
BMWRITE);
MinhaImagem := TJPEGImage.Create;
MinhaImagem.LoadFromFile(Dialog.FileName);
MinhaImagem.SaveToStream(BS);
Foto.Picture.Assign(MinhaImagem);
BS.Free;
MinhaImagem.Free;
Tabela.Post;
DBISaveChanges(Tabela.Handle);
End;
End;
procedure TForm1.Button1Click(Sender: TObject);
begin
Grava_Imagem_JPEG(TbClientes,TbClientesCli_Foto, Image1,
OpenPictureDialog1);
// TbClientes é o nome de alguma Tabela
// TbClientesCli_Foto é um variavel da tabela do tipo Blob
// Image1 é um componente
// OpenPictureDialog1 é o componente para abrir a figura
end;Topo |
52 - Ler imagem
JPG da tabela Paradox
Procedure
Le_Imagem_JPEG(Campo:TBlobField; Foto:TImage);
var BS:TBlobStream;
MinhaImagem:TJPEGImage;
Begin
if Campo.AsString <> '' Then
Begin
BS := TBlobStream.Create((Campo as TBlobField),
BMREAD);
MinhaImagem := TJPEGImage.Create;
MinhaImagem.LoadFromStream(BS);
Foto.Picture.Assign(MinhaImagem);
BS.Free;
MinhaImagem.Free;
End
Else Foto.Picture.LoadFromFile('c:\temp\limpa.jpg');
End;
procedure TForm1.Button1Click(Sender: TObject);
begin
Le_Imagem_JPEG(TbClientesCli_Foto, Image1);
// TbClientesCli_Foto é um variavel da tabela do tipo Blob
// Image1 é um componente
end;
Topo |
53 - Como
saber onde esta instalado o Windows
function
TForm1.DirWindows : string;
var Dir : array[0..255] of char;
begin
GetWindowsDirectory(Dir, 255);
Result := StrPas(Dir);
end; {DirWindows}
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := DirWindows;
end;Topo |
54 - Como saber
quantos dias tem no mes
function
TForm1.AnoBiSexto(AYear: Integer): Boolean;
begin
// Verifica se o ano é Bi-Sexto
Result := (AYear mod 4 = 0) and ((AYear mod 100 <> 0) or
(AYear mod 400 = 0));
end;
function TForm1.DiasPorMes(AYear, AMonth: Integer): Integer;
const DaysInMonth: array[1..12] of Integer = (31, 28, 31, 30, 31, 30,
31, 31, 30, 31, 30, 31);
begin
Result := DaysInMonth[AMonth];
if (AMonth = 2) and AnoBiSexto(AYear) then
Inc(Result);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
Label1.Caption := IntToStr(DiasPorMes(1999, 10));
end;Topo |
55 - Como saber se
o ano é bisexto
function
TForm1.AnoBiSexto(AYear: Integer): Boolean;
begin
Result := (AYear mod 4 = 0) and ((AYear mod 100 <> 0) or
(AYear mod 400 =
0));
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
if AnoBiSexto(1999) Then
ShowMessage('Ano de 1999 é Bisexto')
Else ShowMessage('Ano de 1999 não é Bisexto');
end;Topo |
56 - Como saber
qual o dia da Semana
case
DayOfWeek(date) of
1: ShowMessage('Hoje é Domingo ');
2: ShowMessage('Hoje é Segunda Feira');
3: ShowMessage('Hoje é Terça Feira');
4: ShowMessage('Hoje é Quarta Feira');
5: ShowMessage('Hoje é Quinta Feira');
6: ShowMessage('Hoje é Sexta Feira');
7: ShowMessage('Hoje é Sabado');
end;
Topo |
57 - Colocar o mes por
extenso
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
function MesExtenso( Mes:Word ) : string;
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
function TForm1.MesExtenso( Mes:Word ) : string;
const meses : array[0..11] of PChar = ('Janeiro', 'Fevereiro', 'Março',
'Abril', 'Maio', 'Junho', 'Julho',
'Agosto', 'Setembro','Outubro',
'Novembro', 'Dezembro');
begin
result := meses[mes-1];
End;
procedure TForm1.Button1Click(Sender: TObject);
begin
label1.Caption := MesExtenso(3);
end;
end. Topo |
58 - Como
cancelar um loop (while, for ou repeat)
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
btIniciar: TButton; // um botão para Iniciar
btCancelar: TButton; // um botão para cancelar
Label1: TLabel;
Label2: TLabel;
procedure btIniciarClick(Sender: TObject);
procedure btCancelarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
cancelar : Boolean;
implementation
{$R *.DFM}
procedure TForm1.btIniciarClick(Sender: TObject);
var I :Integer;
begin
For I:= 1 to 100000 do
Begin
Label1.Caption := 'Registros : '+IntToStr(I);
Application.ProcessMessages;
if Cancelar Then
Begin
Cancelar := False;
if MessageDlg('Deseja
Cancelar ?',mtConfirmation,
[mbYes,mbNo],0) = mrYes Then
Begin
Label2.Caption := 'Registro cancelado';
Abort;
End;
End;
End;
end;
procedure TForm1.btCancelarClick(Sender: TObject);
begin
Cancelar := True;
end;
end. Topo |
59 - Como
traduzir as mensagens do Delphi
O Delphi 3 não possui os arquivos de recursos (.RC) com as mensagens para serem
traduzidas, porém, pode ser encontrado no diretório DOC do próprio Delphi 3 os arquivos
com a extensão .INT. Estes arquivos contém as mensagens e podem ser abertos com o
WordPad. Após traduzidas as mensagens desejadas, devemos salvar o arquivo e depois fazer
uma cópia renomeando o arquivo para a extensão .PAS. Com isso teremos uma Unit do
Delphi. Então deveremos abrir esta Unit no Delphi e colocar um END. ao final da Unit,
pois ela não contém isto. Resta então, compilar a Unit.
Após compilada,
teremos um arquivo chamado DBCONSTS.DCU que é o .PAS compilado pelo Delphi. Este arquivo
.DCU deve ser copiado para o diretório LIB do Delphi 3. Pronto !!! Agora temos as
mensagens traduzidas, basta apenas compilar o projeto novamente. Cuidado: Antes de copiar a unit compilada (DCU) para o diretório
LIB do Delphi, não se esqueça de renomear o arquivo .DCU lá existente para um .DC_, por
exemplo, por medida de segurança.
Obs.: Não é
necessário compilar a biblioteca pois as mensagens serão atualizadas conforme forem
recompilados os projetos gerados no Delphi 3.
Topo |
60 - Como
salvar uma tabela fisicamente
na clausula uses
de seu formulário acrescente a unit "DBIProcs" e no evento AfterPost de sua
tabela coloque o seguinte:
DBISaveChanges(Tabela.Handle);Topo |
61 - Inserir tabelas no
Word
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Db, DBTables;
type
TForm1 = class(TForm)
btIniciar: TButton;
Query1: TQuery;
Query1Cid_Codigo: TIntegerField;
Query1Cid_Descricao: TStringField;
Query1Cid_UF: TStringField;
procedure btIniciarClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
uses OleAuto;
{$R *.DFM}
procedure TForm1.btIniciarClick(Sender: TObject);
var Word : Variant;
NumCol,I : Integer;
begin
NumCol := Query1.FieldCount;
Word := CreateOleObject('Word.Basic');
word.appshow;
word.filenew;
While not Query1.EOF do
Begin
For I:=1 to Query1.fieldcount-1 do
word.Insert(Query1.fields[i].AsString+#9);
Query1.Next;
End;
Word.editselectall;
Word.TextToTable(ConvertFrom := , NumColumns := NumCol);
word.TableSelectTable;
Word.TableSelectRow;
Word.TableHeadings(1);
Word.TableAutoFormat(Format:=16,HeadingRows:=1);
Word.edit;
end;
end. Topo |
64 - Fazer o
formulário redondo
procedure
TForm1.FormCreate(Sender: TObject);
var Hd : THandle;
begin
Hd := CreateEllipticRgn(0,0,400,400);
SetWindowRgn(Handle,Hd,True);
end;
Topo |
65 - Listar todos os
programas que estão sendo executados pelo Windows
Function
EnumWindowsProc(Wnd : HWND; lb:TListBox) : BOOL; stdcall;
var caption : Array[0..128] of char;
Begin
Result := True;
if isWindowVisible(Wnd) and ((GetWindowLong(Wnd, GWL_HWNDPARENT) = 0) or
(HWND(GetWindowLong(Wnd, GWL_HWNDPARENT)) = GetDeskTopWindow))
And
((GetWindowLong(Wnd, GWL_EXSTYLE) and WS_EX_TOOLWINDOW) = 0) Then
Begin
SendMessage(Wnd,WM_GETTEXT,SizeOf(caption),integer(@caption));
lb.Items.AddObject(Caption,TObject(Wnd));
End;
End;
procedure TForm1.Button2Click(Sender: TObject);
begin
ListBox.Items.Clear;
ENumWindows(@EnumWindowsProc,integer(ListBox1));
end;Topo |
68 - Habilitar
a tecla ENTER para cada formulário
Primeiramente não
pode esquecer de colocar a propriedade do KeyPreview do formulário para True, este evento
não funciona para todos os formulários e sim para cada um individualmente.procedure
TForm1.FormKeyPress(Sender: TObject; var Key: Char);
begin
if (Key = Chr(13)) Then
Begin
Perform(wm_NextDlgCtl,0,0);
Key := #0;
End;
end;
Topo |
69 - Lendo e
gravando em arquivo texto
procedure
TForm1.Button1Click(Sender: TObject);
var Texto: String;
ArquivoTexto: TextFile; {handle do arquivo texto}
begin
// Associa o arquivo a uma variável do tipo
TextFile
AssignFile(ArquivoTexto,'C:\temp\texto.txt');
ReWrite(ArquivoTexto); {Recria o arquivo texto}
Writeln(ArquivoTexto,'TESTANDO'); // Grava no arquivo texto
Writeln(ArquivoTexto,'TESTANDO 1'); // Grava no arquivo texto
Writeln(ArquivoTexto,'TESTANDO 2'); // Grava no arquivo texto
Writeln(ArquivoTexto,'TESTANDO 3'); // Grava no arquivo texto
CloseFile(ArquivoTexto); {Fecha o arquivo texto}
end;
Topo |
70 - Imprimir em impressora
matricial em modo caracter via Rede
// Esta rotina lê
todas as impressoras instaladas no windows
// e coloca dentro de um ComboBox e não se esqueça de adicionar
// na cláusula uses a unit Printers
procedure TForm1.FormShow(Sender: TObject);
var I : Integer;
begin
ComboBox1.Items.Clear;
For I:= 1 to Printer.Printers.Count do
Begin
if Pos('LPT', printer.Printers.Strings[I-1]) > 0Then
ComboBox1.Items.Add('LPT1')
Else if Pos('\\', printer.Printers.Strings[I-1]) > 0
Then
ComboBox1.Items.Add(Copy(printer.Printers.Strings[I-1],
Pos('\\', printer.Printers.Strings[I-1]),
length(printer.Printers.Strings[I-1]) -
Pos('\\', printer.Printers.Strings[I-1]) + 1));
End;
End;// e quando apertar
o botao imprimir, o evento pega qual a impressora
// que você escolheu atravéz do ComboBox e Imprimi.
procedure TForm1.btImprimirClick(Sender: TObject);
var I:Integer;
Arquivo : TextFile;
begin
AssignFile(Arquivo,ComboBox1.Value);
Rewrite(Arquivo);
WriteLn(Arquivo, 'TESTE DE IMPRESSAO - 1');
WriteLn(Arquivo, 'TESTE DE IMPRESSAO - 2');
WriteLn(Arquivo, 'TESTE DE IMPRESSAO - 3');
WriteLn(Arquivo, 'TESTE DE IMPRESSAO - 4');
CloseFile(Arquivo);
end;
Topo |
71 - Como
abrir e fechar o drive de CD-ROM
// coloque na
cláusula uses a unit MMSystem
procedure TForm1.BitBtn1Click(Sender: TObject);
begin
// Para abrir
mciSendString ('Set cdaudio door open wait', nil, 0, handle);
// Para Fechar
mciSendString ('Set cdaudio door closed wait', nil, 0, handle);
end;
Topo |
72 - Como
criar 1 disco apenas para o BDE
Arquivos Exenciais para o BDE:
EUROPE.BLL
USA.BLL
IDR20009.DLL
IDAPI32.DLL
BLW32.DLL
IDAPI32.CFG - Esse arquivo não precisa ter este nome, mas precisa ser configurado no
registro do Windows
Drivers de Banco de Dados:
IDPDX32.DLL - Driver Paradox
IDASCI32.DLL - Driver ASCII
IDDBAS32.DLL - Driver DBase
IDODBC32.DLL - Driver ODBCO BDE precisa de pelo menos um Driver de Banco
de Dados para funcionar.
Pegue o programa p_registro.zip para registrar
este disco no Registro do Windows
Topo |
|