Escolar Documentos
Profissional Documentos
Cultura Documentos
APOSTILA
DICAS DE PROGRAMAO DELPHI
Araras/SP
2013
Pgina 1
Funes para o Delphi
SUMRIO
Pgina 2
Funes para o Delphi
Pgina 3
Funes para o Delphi
Pgina 4
Funes para o Delphi
Arquivos Paradox podem ser compartilhados em rede. Para que isto ocorra
devemos:
1. Adicionar o DATABASE ENGINE CONFIGURATION (BDE CONFIG)
2. Selecionar a pgina DRIVERS
3. Selecionar o driver PARADOX e alterar o parmetro NET DIR para o local onde
sero gravados os arquivos de controle para compartilhamento. Por exemplo,
"G:\MEUAPLIC", onde G : corresponde ao drive de rede e MEUAPLIC, o diretrio
aonde est o aplicativo (executvel)
4. Depois selecionar a pgina SYSTEM
5. Alterar o parmetro LOCAL SHARE para TRUE. Aps isto o BDE controlar o
compartilhamento de arquivos PARADOX em rede.
Confirmar o diretrio
procedure TForm1.Button1Click(Sender: TObject);
begin
if DirectoryExists(Edit1.Text) then
Label1.Caption := Edit1.Text + ' exists'
else Label1.Caption := Edit1.Text + ' does not exist';
end;
Pgina 5
Funes para o Delphi
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 TemDiscoNoDrive('a') then
ShowMessage('Tem disco no drive A:')
else ShowMessage('No tem disco no drive A:');
end;
Pgina 6
Funes para o Delphi
Depois de criar os dois forms, clique no menu View, na opo Project Source.
Encontrando a linha em que o form de abertura criado e apague-a.
Agora insira as linhas abaixo antes da criao dos demais form do seu aplicativo:
begin
AberturaForm:=TFormAbertura.Create(Application);
AberturaForm.show; {Os outros form devem ser criados a partir daqui}
FormAbertura.Hide; {Esconde o FormAbertura}
FormAbertura.Free; {Libera Memria}
Application.Run;
End;
Pgina 7
Funes para o Delphi
Capturar tela
procedure TForm1.Button1Click(Sender: TObject);
var
BackgroundCanvas : TCanvas;
Background : TBitmap; {bitmap holding the background }
DC : hDC;
begin
// get the background bitmap
Background:= TBitmap.Create;
Background.Width:= Width;
Background.Height:= Height;
DC:= GetDC (0);
BackgroundCanvas:= TCanvas.Create;
BackgroundCanvas.Handle:= DC;
// stretch the bitmap to the display size (it could be much smaller (preview))
Background.Canvas.CopyRect(Rect (0, 0, Width, Height), BackgroundCanvas, Rect
(0, 0, Screen.Width, Screen.Height));
BackgroundCanvas.Free;
image1.Picture.Bitmap:= Background;
end;
// Habilita
var
Registry: TRegistry;
begin
Registry := TRegistry.Create;
Registry.RootKey := HKEY_CURRENT_USER;
Registry.OpenKey('\Control Panel\Desktop', TRUE);
Registry.WriteInteger('ScreenSaveUsePassword',$0);
Registry.CloseKey;
Registry.Free;
end;
Pgina 8
Funes para o Delphi
// Desabilita
Sobrescrevendo um evento
Para executar algo antes do evento Showmodal por exemplo, utilize o seguinte:
public
function showmodal: integer;
function TMeuForm.Showmodal : integer;
begin
{ Aqui vai tudo que se precisa fazer antes }
result := inherited showmodal;
end;
Pgina 9
Funes para o Delphi
Como utilizar:
procedure TForm1.Button1Click(Sender: TObject);
begin
ParadoxPack(table1);
end;
Pgina 10
Funes para o Delphi
Result := Locked;
// If the current session does not have a lock and the ByAnyone varable is
// set to check all sessions, continue check...
if (Result = False) and (ByAnyone = True) then
begin
// Get a new cursor to the same record...
Check(DbiCloneCursor(Table.Handle, False, False, hCur));
try
// Try and get the record with a write lock...
rslt := DbiGetRecord(hCur, dbiWRITELOCK, nil, nil);
if rslt <> DBIERR_NONE then
begin
// if an error occured and it is a lock error, return true...
if HiByte(rslt) = ERRCAT_LOCKCONFLICT then
Result := True
else
// If some other error happened, throw an exception...
Check(rslt);
end
else
// Release the lock in this session if the function was successful...
Check(DbiRelRecordLock(hCur, False));
finally
// Close the cloned cursor...
Check(DbiCloseCursor(hCur));
end;
end;
end;
Como utilizar:
procedure TForm1.Button1Click(Sender: TObject);
begin
If IsRecordLocked(Table1,True) then
Showmessage('Registro Travado!');
end;
Pgina 11
Funes para o Delphi
Cursor customizado
Criar um arquivo de recurso com o cursor (vamos cham-lo de teste.res)
Vamos chamar o recurso de CUR_1
Coloque {$R teste.res} na seo implementation
Criando atalhos
Inclua as units ShlObj, ActiveX, ComObj, Registry na clausula uses do seu form.
Pgina 12
Funes para o Delphi
Pgina 13
Funes para o Delphi
Apagar um subdiretrio
Inclua a unit SHELLAPI na clausula uses do seu form.
Como utilizar:
procedure TForm1.Button1Click(Sender: TObject);
begin
DeleteDir( Self.Handle,'C:\TESTE');
end;
Testar a impressora
Function TForm1.PrinterOnLine : Boolean;
Const
PrnStInt : Byte = $17;
StRq : Byte = $02;
PrnNum : Word = 0; { 0 para LPT1, 1 para LPT2, etc. }
Var
nResult : byte;
Begin
Asm
mov ah,StRq;
mov dx,PrnNum;
Int $17;
Pgina 14
Funes para o Delphi
mov nResult,ah;
end;
PrinterOnLine := (nResult and $80) = $80;
end;
Como utilizar:
procedure TForm1.Button1Click(Sender: TObject);
begin
If not PrinterOnLine then ShowMessage('Verifique a Impressora!');
end;
Validar datas
try
StrToDate(Edit1.Text);
except
on EConvertError do
ShowMessage ('Data Invlida!');
end;
Procurar arquivos
procedure TForm1.DirList( ASource : string; ADirList : TStringList );
var
SearchRec : TSearchRec;
Result : integer;
begin
Result := FindFirst( ASource, faAnyFile, SearchRec );
if Result = 0 then
while (Result = 0) do
begin
if (SearchRec.Name+' ')[1] = '.' then
{ Se pegou nome de SubDiretorio }
begin
Result := FindNext( SearchRec );
Continue;
end;
ADirList.Add( SearchRec.Name );
Result := FindNext( SearchRec );
end;
FindClose( SearchRec );
ADirList.Sort;
end;
Pgina 15
Funes para o Delphi
Como utilizar:
procedure TForm1.Button1Click(Sender: TObject);
var
contador: Integer;
lista: TStringlist;
begin
lista:= TStringlist.create;
DirList('C:\*.*', lista);
end;
Pgina 16
Funes para o Delphi
Como utilizar:
procedure TForm1.Button1Click(Sender: TObject);
begin
ExecFile('c:\windows\ladrilhos.bmp');
end;
Pgina 17
Funes para o Delphi
// habilita
procedure showTaskbar;
var wndHandle : THandle;
wndClass : array[0..50] of Char;
begin
StrPCopy(@wndClass[0], 'Shell_TrayWnd');
wndHandle:= FindWindow(@wndClass[0], nil);
ShowWindow(wndHandle, SW_RESTORE);
end;
// habilita
procedure TForm1.Button2Click(Sender: TObject);
var
numero: integer;
begin
SystemParametersInfo(97,Word(false),@numero,0);
end;
Pgina 18
Funes para o Delphi
Como utilizar:
procedure TForm1.Button1Click(Sender: TObject);
begin
edit1.text:= inttostr(TamArquivo('CAMINHO\NOMEDOARQUIVO'));
end;
Image1.Picture.Icon.Handle:= ExtractIcon(Handle,PChar('c:\windows\calc.exe'),0);
Verificando a memria
var
MemoryStatus: TMemoryStatus;
begin
MemoryStatus.dwLength:= sizeof(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
Label1.Caption := 'Total de memria fsica : ' +
IntToStr(MemoryStatus.dwTotalPhys);
end;
Pgina 19
Funes para o Delphi
Nmero de srie do hd
Function TForm1.SerialNum(FDrive:String) :String;
var
Serial: DWord;
DirLen, Flags: DWord;
DLabel : Array[0..11] of Char;
begin
Try
GetVolumeInformation(PChar(FDrive+':\'),dLabel,12,@Serial,DirLen,Flags,nil,0);
Result := IntToHex(Serial,8);
Except
Result := '';
end;
end;
CASE ERR of
ERROR_ACCESS_DENIED : ShowMessage ( 'Acesso negado.' );
ERROR_ALREADY_ASSIGNED : ShowMessage ( 'A letra do drive especificada j
est conectada.' );
ERROR_BAD_DEV_TYPE : ShowMessage ( 'O tipo de dispositivo e o tipo de
recurso no so compatveis.' );
ERROR_BAD_DEVICE : ShowMessage ( 'Letra invlida.' );
ERROR_BAD_NET_NAME : ShowMessage ( 'Nome do servidor no vlido ou no
pode ser localizado.' );
ERROR_BAD_PROFILE : ShowMessage ( 'Formato incorreto de parmetros.' );
ERROR_CANNOT_OPEN_PROFILE : ShowMessage ( 'Conexo permanente no
disponvel.' );
ERROR_DEVICE_ALREADY_REMEMBERED : ShowMessage ( 'Uma entrada para
o dispositivo especificado j est no perfil do usurio.' );
ERROR_EXTENDED_ERROR : ShowMessage ( 'Erro de rede.' );
ERROR_INVALID_PASSWORD : ShowMessage ( 'Senha especificada invlida.' );
ERROR_NO_NET_OR_BAD_PATH : ShowMessage ( 'A operao no foi concluda
porque a rede no foi inicializada ou caminho invlido.' );
ERROR_NO_NETWORK : ShowMessage ( 'A rede no est presente.' );
Pgina 20
Funes para o Delphi
Como utilizar:
procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage(usuario)
end;
saber o estado das teclas Num lock, Caps lock e Scroll lock
Para saber o estado das teclas acima citadas, utilize a funo getkeystate em
conjunto com o cdigo das teclas, ela retorna 0 se a tecla estiver OFF e 1 se a tecla
estiver ON, assim:
Testando drives
function TForm1.TemDiscoNoDrive(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);
Pgina 21
Funes para o Delphi
try
if DiskSize(DriveNumero-$40) <> -1 then
Result := true
else
messagebeep(0);
finally
SetErrorMode(EMode);
end;
end;
Como utilizar:
procedure TForm1.Button1Click(Sender: TObject);
begin
if TemDiscoNoDrive('a') then
ShowMessage('Tem disco no drive A:')
else
ShowMessage('No tem disco no drive A:');
end;
Tipo_de_Janela :
SndPlaySound('C:\Windows\Media\Som.wav',SND_ASYNC);
Pgina 22
Funes para o Delphi
Procedure TForm1.LeIni( Var Numero : Longint ; Var Texto : String ; Var Condicao :
Boolean);
var
ArqIni : tIniFile;
begin
ArqIni := tIniFile.Create('c:\windows\temp\Teste.Ini');
Try
Numero := ArqIni.ReadInteger('Dados', 'Numero', Numero );
Texto := ArqIni.ReadString('Dados', 'Texto', Texto );
Condicao := ArqIni.ReadBool('Dados', 'Condio', Condicao );
Finally
ArqIni.Free;
end;
end;
Como utilizar:
procedure TForm1.Button1Click(Sender: TObject);
begin
GravaIni(1234,'TESTE',True);
end;
Exponenciao
Inclua a unit Math na clausula uses do seu form. Depois disso utilize a funo Power.
Edit1.text:= FloatToStr(Power(2,4));
Pgina 23
Funes para o Delphi
begin
Pgina 24
Funes para o Delphi
...
Application.CreateForm(TAberturaForm, AberturaForm); // Esta linha deve ser
apagada
...
end;
Aps remover a linha acima, insira as linhas abaixo antes da criao dos demais
formulrios do seu aplicativo:
begin
AberturaForm:= TAberturaForm.Create(Application);
AberturaForm.show
{Os demais formulrios devem ser criados aqui}
...
AberturaForm.Hide;
AberturaForm.Free;
Application.Run;
End;
Os comandos...
Pgina 25
Funes para o Delphi
Pgina 26
Funes para o Delphi
Como utilizar:
Procedure TForm1.Button1Click (Sender: TObject);
Begin
FindReplace(Edit1.Text,Edit2.Text, Memo1);
end;
Pgina 27
Funes para o Delphi
DBGrid1.Canvas.Brush.Color:= clAqua;
DBGrid1.Canvas.Font.Color:= clWindowText;
DBGrid1.Canvas.FillRect(Rect);
DBGrid1.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
end;
end;
var
contador: Integer;
begin
With Dbgrid1 do
Begin
for contador:= 0 to Pred(SelectedRows.Count) do
Begin
Datasource.Dataset.Bookmark:= SelectedRows[contador]; // posiciona nos registros
selecionados do DBGrid
end;
end;
Pgina 28
Funes para o Delphi
Commit (Delphi 3)
Inclua DBISaveChanges(Nome da Tabela.handle) no evento After Post. Inclua em
uses a biblioteca DBIProcs.
Commit (Delphi 2)
Inclua DBISaveChanges(Nome da Tabela.handle) no evento After Post. Inclua em
uses a biblioteca DBIProcs.
Pgina 29
Funes para o Delphi
Criando tabelas
var
Tabela: TTable;
Indices: TIndexOptions;
begin
Tabela:= TTable.Create;
Indices:= [ixPrimary, IxUnique];
with Tabela do
begin
active:= false;
databasename:= 'c:\teste';
tablename:= 'Tabela';
tabletype:= ttDefault;
fielddefs.clear;
fielddefs.add('Codigo', ftInteger, 0, false);
...
indexdefs.clear;
indexdefs.add('Codigo_Chave', 'codigo', Indices);
CreateTable;
end;
Pgina 30
Funes para o Delphi
Pgina 31
Funes para o Delphi
Pgina 32
Funes para o Delphi
With QryExtrato do
while not EOF do
begin
Excel.WorkBooks[1].Sheets[1].Cells[Linha,1] :=
QuotedStr(FieldByName('cdbeneficiario').AsString);
Excel.WorkBooks[1].Sheets[1].Cells[Linha,2] :=
FieldByName('novendedor').Value;
Excel.WorkBooks[1].Sheets[1].Cells[Linha,3] :=
FieldByName('notiponegociacao').Value;
Excel.WorkBooks[1].Sheets[1].Cells[Linha,4] := FieldByName('nome').Value;
Pgina 33
Funes para o Delphi
Excel.WorkBooks[1].Sheets[1].Cells[Linha,5] :=
FieldByName('num_titular').AsInteger;\
// adicione os campos desejados, seguindo a seqncia acima
Linha := Linha + 1;
Next;
end;
Pgina 34
Funes para o Delphi
{ Pega o numero da coluna, aumente o 3 no final se tiver mais que 999 colunas... }
vNroColum := StrToInt( Copy( vNomeMenu, Pos('_', vNomeMenu) + 1 , 3));
Exemplo no Oracle:
Var
qry_Codigo : TADOQuery;
begin
if DseVenda.state in [DsInsert] then
begin
//Recupera o cdigo da venda do banco de dados utilizando a sequencia criada
qry_Codigo := TADOQuery.Create(Self);
qry_Codigo.Connection := frm_Menu.Connection;
qry_Codigo.SQL.Add('Select custom.seq_venda.nextval from dual');
qry_Codigo.Open;
DseVenda.FieldByName('cdvenda').Value :=
Pgina 35
Funes para o Delphi
qry_Codigo.FieldByName('NEXTVAL').Value;
qry_Codigo.Free;
end;
Exemplo no Interbase:
Var
Qry_ID : TADOQuery;
begin
Try
Qry_ID := TADOQuery.Create(Self);
Qry_ID.Connection := frm_Menu.Connection;
Qry_ID.SQL.Add('select gen_id(GEN_CLIENTE, 1) from rdb$database');
Qry_ID.Open;
DsePrincipal.FieldByName('id').AsInteger :=
Qry_ID.FieldByName('gen_id').AsInteger;
DsePrincipal.FieldByName('dtcadastro').AsDateTime := Date;
CmbClassificacao.SetFocus;
Qry_ID.Free;
except
ShowMessage('Erro ao gerar ID. Contacte o suporte tcnico.');
Qry_ID.Free;
end;
begin
if (Msg.Message = wm_SysCommand) and (Msg.wParam = sc_ScreenSave) then
Handled := true;
end;
Pgina 36
Funes para o Delphi
Gira o texto
Procedure TForm1.Button1Click(Sender: TObject);
var
lf : TLogFont;
tf : TFont;
i : integer;
begin
with Form1.Canvas do
begin
Font.Name := 'Verdana';
Font.Size := 16;
tf := TFont.Create;
tf.Assign(Font);
GetObject(tf.Handle, sizeof(lf), @lf);
lf.lfOrientation := 1000;
end;
For i:= 50000 Downto 1 do
Begin
lf.lfEscapement := i;
tf.Handle := CreateFontIndirect(lf);
Form1.Canvas.Font.Assign(tf);
Form1.Canvas.TextOut(200, Height div 2, 'Edgar da Cruz');
//Sleep(10); Este pode cria um Delay na execuo
end;
tf.Free;
end;
Hint Redondo
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Commctrl, ExtCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Panel1: TPanel;
procedure FormCreate(Sender: TObject);
Pgina 37
Funes para o Delphi
private
{ Private declarations }
public
{ Public declarations }
end;
const
TTS_BALLOON = $40;
TTM_SETTITLE = (WM_USER + 32);
var
Form1: TForm1;
hTooltip: Cardinal;
ti: TToolInfo;
buffer : array[0..255] of char;
implementation
{$R *.DFM}
Pgina 38
Funes para o Delphi
begin
lpti.hwnd := Item;
lpti.Rect := Rect;
lpti.lpszText := Text;
SendMessage(hToolTip, TTM_ADDTOOL, 0, Integer(lpti));
FillChar(buffer, sizeof(buffer), #0);
lstrcpy(buffer, Title);
if (IconType > 3) or (IconType < 0) then IconType := 0;
SendMessage(hToolTip, TTM_SETTITLE, IconType, Integer(@buffer));
end;
end;
end;
end.
end.
Observao:
TipoDoIcone pode ser:
0 - Sem cone
1 - Informao
2 - Aviso
3 - Erro
Pgina 39
Funes para o Delphi
const
ID_BIT=$200000; // EFLAGS ID bit
SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread,THREAD_PRIORITY_TIME_CRITICAL);
Sleep(10);
asm
dw 310Fh // rdtsc
mov TimerLo, eax
mov TimerHi, edx
end;
Sleep(DelayTime);
asm
dw 310Fh // rdtsc
sub eax, TimerLo
sbb edx, TimerHi
mov TimerLo, eax
mov TimerHi, edx
end;
SetThreadPriority(GetCurrentThread, Priority);
SetPriorityClass(GetCurrentProcess, PriorityClass);
Pgina 40
Funes para o Delphi
var cpuspeed:string;
begin
cpuspeed:=Format('%f MHz', [GetCPUSpeed]);
edit1.text := cpuspeed;
end;
Para esconder:
ShowWindow(FindWindow(nil,'Program Manager'),SW_HIDE);
Para mostrar:
ShowWindow(FindWindow(nil,'Program Manager'),SW_SHOW);
Pgina 41
Funes para o Delphi
Como utilizar:
Image1.picture.Assign(CaptureScreenRect(Rect(0,0,Width,Height)));
Pgina 42
Funes para o Delphi
end;
Pgina 43
Funes para o Delphi
begin
wsoma := wsoma + (wm11 *strtoint(copy(Dado,11 - I, 1)));
if wm11 < 9 then
begin
wm11 := wm11+1
end
else
begin
wm11 := 2;
end;
end;
wdigito := 11 - (wsoma MOD 11);
if wdigito > 9 then
begin
wdigito := 0;
end;
if wdv = wdigito then
begin
validapis := true;
end
else
begin
validapis := false;
end;
end;
end;
DataNasc:=StrToDate(Nasc.Text);
DecodeDate(DataNasc,NAno,NMes,NDia);
Dia:=(HDia - NDia);
Pgina 44
Funes para o Delphi
Mes:=(HMes - NMes);
Ano:=(HAno - NAno);
end;
Pgina 45
Funes para o Delphi
DbGrid zebrado
O exemplo abaixo mostra como deixar cada linha do componente DBGrid de uma
cor diferente, dando assim um efeito zebrado. O controle feito no evento
OnDrawColumnCell.
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, DBTables, Grids, DBGrids, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
DBGrid1: TDBGrid;
Table1: TTable;
DataSource1: TDataSource;
procedure DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
Pgina 46
Funes para o Delphi
If odd(Table1.RecNo) then
begin
DBGrid1.Canvas.Font.Color:= clWhite;
DBGrid1.Canvas.Brush.Color:= clGreen;
end
else
begin
DBGrid1.Canvas.Font.Color:= clBlack;
DBGrid1.Canvas.Brush.Color:= clWhite;
end;
DBGrid1.Canvas.FillRect(Rect);
DBGrid1.Canvas.TextOut(Rect.Left+2,Rect.Top,Column.Field.AsString);
end;
type
TForm1 = class(TForm)
private
{ Private declarations }
procedure WMGetMinMaxInfo(var Msg: TWMGetMinMaxInfo);
message WM_GETMINMAXINFO;
procedure WMInitMenuPopup(var Msg: TWMInitMenuPopup);
message WM_INITMENUPOPUP;
procedure WMNCHitTest(var Msg: TWMNCHitTest);
message WM_NCHitTest;
public
{ Public declarations }
end;
var
Form1: TForm1;
Pgina 47
Funes para o Delphi
implementation
{$R *.DFM}
procedure TForm1.WMGetMinMaxInfo(var Msg: TWMGetMinMaxInfo);
begin
inherited;
with Msg.MinMaxInfo^ do
begin
ptMinTrackSize.x:= form1.width;
ptMaxTrackSize.x:= form1.width;
ptMinTrackSize.y:= form1.height;
ptMaxTrackSize.y:= form1.height;
end;
end;
procedure TForm1.WMInitMenuPopup(var Msg: TWMInitMenuPopup);
begin
inherited;
if Msg.SystemMenu then
EnableMenuItem(Msg.MenuPopup, SC_SIZE, MF_BYCOMMAND or MF_GRAYED)
end;
procedure TForm1.WMNCHitTest(var Msg: TWMNCHitTest);
begin
inherited;
with Msg do
if Result in [HTLEFT, HTRIGHT, HTBOTTOM,
HTBOTTOMRIGHT,HTBOTTOMLEFT, HTTOP,
HTTOPRIGHT, HTTOPLEFT] then
Result:= HTNOWHERE
end;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure Button1MouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure Button1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
private
{ Private declarations }
Pgina 48
Funes para o Delphi
public
{ Public declarations }
MouseDownSpot : TPoint;
Capturing : bool;
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
// Evento OnMouseDown do Form
procedure TForm1.Button1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if ssCtrl in Shift then begin
SetCapture(Button1.Handle);
Capturing := true;
MouseDownSpot.X := x;
MouseDownSpot.Y := Y;
end;
end;
// Evento OnMouseMove do Form
procedure TForm1.Button1MouseMove(Sender:
TObject; Shift: TShiftState; X, Y: Integer);
begin
if Capturing then begin
Button1.Left:= Button1.Left-(MouseDownSpot.x-x);
Button1.Top:= Button1.Top - (MouseDownSpot.-y);
end;
end;
// Evento OnMouseUp do Form
procedure TForm1.Button1MouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if Capturing then begin
ReleaseCapture;
Capturing := false;
Button1.Left := Button1.Left - (MouseDownSpot.x -x);
Button1.Top := Button1.Top - (MouseDownSpot.y - y);
end;
end;
Pgina 49
Funes para o Delphi
Pgina 50
Funes para o Delphi
Pgina 51
Funes para o Delphi
Pgina 52
Funes para o Delphi
Y: Integer);
begin
Edit1.hint := Primeira Linha+#13+Segunda Linha+#13+
Terceira Linha+#13+Quarta Linha;
end;
Obs. No esquecer de mudar para TRUE o evento ShowHint.
Pgina 53
Funes para o Delphi
Application.OnHint := DisplayHint;
end;
procedure TForm1.DisplayHint(Sender: TObject);
begin
Panel1.Caption := Application.Hint;
end;
Obs. No necessrio Atribuir True para o ShowHint
Pgina 54
Funes para o Delphi
DIR do drive PARADOX o local onde esto as bases de dados e na PATH do Alias
especificar o caminho das base de dados. Mas muita ateno, todas as estaes
devem estar com a mesma configurao do BDE. Veja o exemplo abaixo para
configurao do parmetro NET DIR do drive PARADOX e o PATH do Alias.
Estao n.1
NET DIR F:\
Path do Alias F:\DIRETORIO
Estao n.2
NET DIR F:\
Path do Alias F:\DIRETORIO
Estao n.3
NET DIR F:\
Path do Alias F:\DIRETORIO
No aconselhvel que os aplicativos feitos em Delphi 1, sejam executados no
servidor da base de dados, pois o PARADOX apresenta problemas de corrupo de
arquivos e ndices neste caso. aconselhvel que no servidor voc coloque
somente as bases de dados. Mas caso voc tenha necessidade de utilizar o servidor
voc pode utilizar uma soluo alternativa para o problema do PARADOX, esta
soluo esta sendo satisfatria na maioria dos casos. Digamos que a letra do drive
de rede que voc vai acessar o servidor, seja a letra F:, ento, faa 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 instalao e configurao do aplicativo e do BDE.
Veja abaixo os exemplos da configurao do BDE p/ Delphi 2 e 3:
Servidor Estao 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
Estao 2 Estao 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 executvel pode ser colocado em cada mquina da rede, diminuindo assim o
trfego de rede.
Pgina 55
Funes para o Delphi
Pgina 56
Funes para o Delphi
Pgina 57
Funes para o Delphi
Pgina 58
Funes para o Delphi
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;
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];
Pgina 59
Funes para o Delphi
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;
Pgina 60
Funes para o Delphi
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;
Pgina 61
Funes para o Delphi
Pgina 62
Funes para o Delphi
Canvas.MoveTo (
XCenter - Round (BackRadius * Cos (Angle)),
YCenter - Round (BackRadius * Sin (Angle)));
Canvas.LineTo (
XCenter + Round (Radius * Cos (Angle)),
YCenter + Round (Radius * Sin (Angle)));
end;
// Evento OnCreate do Form
procedure TForm1.FormCreate(Sender: TObject);
begin
{l as horas antes do formulrio ser exibido}
Timer1Timer (self);
end;
// Evento OnResize do Form
procedure TForm1.FormResize(Sender: TObject);
begin
Refresh;
end;
Pgina 63