Escolar Documentos
Profissional Documentos
Cultura Documentos
APOSTILA
DICAS DE PROGRAMAO DELPHI
Araras/SP
2013
Pgina 1
SUMRIO
Acessando arquivos Paradox em rede ............................................................................................................. 5
Confirmar o diretrio............................................................................................................................................. 5
Hint com quebra de linha ..................................................................................................................................... 5
Testa se existe disco no drive A ...................................................................................................................... 5
Verifica se o Form j est ativo .......................................................................................................................... 6
Pegando o nome do usurio e o nome da empresa no Windows ................................................................ 6
Como criar uma tela de abertura (Splash Screen) .......................................................................................... 7
Como validar a entrada de uma caixa de texto................................................................................................ 7
A tecla ENTER para funcionar como TAB.................................................................................................. 7
Capturar tela .......................................................................................................................................................... 8
Subtrair/adicionar N meses a uma data ............................................................................................................ 8
Data por extenso................................................................................................................................................... 8
Habilitar e desabiliar a senha do protetor de tela ............................................................................................ 8
Sobrescrevendo um evento ................................................................................................................................ 9
Como evitar a mensagem de erro Key Violation ............................................................................................. 9
Como evitar a mensagem de erro Key Violation ............................................................................................. 9
Executar um PACK em tabelas Paradox ........................................................................................................ 10
Verificar se o registro est travado .................................................................................................................. 10
Cursor customizado ........................................................................................................................................... 12
Criando atalhos ................................................................................................................................................... 12
Emular o pressionamento de uma tecla .......................................................................................................... 13
Fechar um aplicativo a partir do Delphi ........................................................................................................... 13
Configurar o Delphi para acessar tabelas do Access ................................................................................... 13
Apagar um subdiretrio...................................................................................................................................... 14
Testar a impressora ........................................................................................................................................... 14
Validar datas........................................................................................................................................................ 15
Procurar arquivos ............................................................................................................................................... 15
Abrir arquivos com aplicativo associado ......................................................................................................... 16
Fazer um TEdit aceitar apenas nmeros ........................................................................................................ 17
Alterar o papel de parede do Windows ........................................................................................................... 17
Extrair o nmero de cores do modo de vdeo corrente................................................................................. 17
Habilitar e desabilitar barra de tarefas............................................................................................................. 17
Habilitar e desabilitar ctrl+alt+del ..................................................................................................................... 18
Alterar a data e a hora do sistema ................................................................................................................... 18
Extrair o tamanho de um arquivo ..................................................................................................................... 19
Extrair o cone de um executvel ..................................................................................................................... 19
Verificando a memria ....................................................................................................................................... 19
Nmero de srie do hd ...................................................................................................................................... 20
Mapear uma pasta na rede ............................................................................................................................... 20
Pegar nome do usurio na rede ....................................................................................................................... 21
saber o estado das teclas Num lock, Caps lock e Scroll lock ...................................................................... 21
Testando drives................................................................................................................................................... 21
Executando programas externos ..................................................................................................................... 22
Reproduzindo sons wav, sem o componente mediaplayer .......................................................................... 22
Manipular arquivos INI ....................................................................................................................................... 22
Exponenciao.................................................................................................................................................... 23
Aguardar um determinado n de segundos .................................................................................................... 24
Tecla ENTER funcionar como TAB ................................................................................................................. 24
Utilizar ponto para separar decimais ............................................................................................................... 24
Criando um Splash Screen (abertura) ............................................................................................................. 24
Como limpar todos os edits de um form ........................................................................................................ 25
Pgina 2
Pgina 3
Pgina 4
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 6
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;
Pgina 8
// Desabilita
procedure TForm1.Button2Click(Sender: TObject);
var
Registry: TRegistry;
begin
Registry := TRegistry.Create;
Registry.RootKey := HKEY_CURRENT_USER;
Registry.OpenKey('\Control Panel\Desktop', TRUE);
Registry.WriteInteger('ScreenSaveUsePassword',$1);
Registry.CloseKey;
Registry.Free;
end;
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
Pgina 11
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
procedure InsereCursor(Num : Smallint);
begin
Screen.Cursors[Num]:= LoadCursor(hInstance, PChar('CUR_1'));
Screen.Cursor := Num;
end;
Criando atalhos
Inclua as units ShlObj, ActiveX, ComObj, Registry na clausula uses do seu form.
Na seo type coloque:
TShortcutPlace = (stDesktop, stStartMenu);
E por fim a procedure para realizar o trabalho:
procedure TForm1.CreateShortcut (FileName, Parameters, InitialDir, ShortcutName,
ShortcutFolder : String; Place: TShortcutPlace);
var
MyObject : IUnknown;
MySLink : IShellLink;
MyPFile : IPersistFile;
Directory : String;
WFileName : WideString;
MyReg : TRegIniFile;
begin
MyObject := CreateComObject(CLSID_ShellLink);
MySLink := MyObject as IShellLink;
MyPFile := MyObject as IPersistFile;
with MySLink do
begin
SetArguments(PChar(Parameters));
SetPath(PChar(FileName));
SetWorkingDirectory(PChar(InitialDir));
end;
MyReg :=
TRegIniFile.Create('Software\MicroSoft\Windows\CurrentVersion\Explorer');
if Place = stDesktop then
Directory := MyReg.ReadString ('Shell Folders','Desktop','');
if Place = stStartMenu then
begin
Pgina 12
Pgina 13
Apagar um subdiretrio
Inclua a unit SHELLAPI na clausula uses do seu form.
procedure DeleteDir( hHandle : THandle; Const sPath : String );
var
OpStruc: TSHFileOpStruct;
FromBuffer, ToBuffer: Array[0..128] of Char;
begin
fillChar( OpStruc, Sizeof(OpStruc), 0 );
FillChar( FromBuffer, Sizeof(FromBuffer), 0 );
FillChar( ToBuffer, Sizeof(ToBuffer), 0 );
StrPCopy( FromBuffer, sPath);
With OpStruc Do
Begin
Wnd:= hHandle;
wFunc:=FO_DELETE;
pFrom:= @FromBuffer;
pTo:= @ToBuffer;
fFlags:= FOF_NOCONFIRMATION;
fAnyOperationsAborted:=False;
hNameMappings:=nil;
//lpszProgressTitle:=nil;
End;
ShFileOperation(OpStruc);
end;
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
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
Pgina 16
Pgina 17
Verificando a memria
var
MemoryStatus: TMemoryStatus;
begin
MemoryStatus.dwLength:= sizeof(MemoryStatus);
GlobalMemoryStatus(MemoryStatus);
Label1.Caption := 'Total de memria fsica : ' +
IntToStr(MemoryStatus.dwTotalPhys);
end;
{typedef struct _MEMORYSTATUS
DWORD dwLength; // sizeof(MEMORYSTATUS)
DWORD dwMemoryLoad; // percentual de memria em uso
DWORD dwTotalPhys; // bytes de memria fsica
DWORD dwAvailPhys; // bytes livres de memria fsica
DWORD dwTotalPageFile; // bytes de paginao de arquivo
DWORD dwAvailPageFile; // bytes livres de paginao de arquivo
DWORD dwTotalVirtual; // bytes em uso de espao de endereo
DWORD dwAvailVirtual; // bytes livres}
Pgina 19
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;
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:
If getkeystate(vk_numlock) = 0 then // Num lock est OFF
If getkeystate(vk_numlock) = 1 then // Num lock est ON
If getkeystate(vk_scroll) = 0 then // Scroll lock est OFF
If getkeystate(vk_scroll) = 1 then // Scroll lock est ON
If getkeystate(vk_CAPITAL) = 0 then // Caps lock est OFF
If getkeystate(vk_CAPITAL) = 1 then // Caps lock est ON
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
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
Pgina 25
Pgina 26
Pgina 28
Commit (Delphi 3)
Inclua DBISaveChanges(Nome da Tabela.handle) no evento After Post. Inclua em
uses a biblioteca DBIProcs.
procedure TForm1.Table1AfterPost(DataSet: TDataSet);
begin
DBISaveChanges(TTable(Dataset).handle);
end;
Commit (Delphi 2)
Inclua DBISaveChanges(Nome da Tabela.handle) no evento After Post. Inclua em
uses a biblioteca DBIProcs.
procedure TForm1.Table1AfterPost(DataSet: TDataSet);
begin
DBISaveChanges(Table1.handle);
end;
Pgina 29
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
Pgina 31
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
Pgina 39
Pgina 42
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}
procedure TForm1.DBGrid1DrawColumnCell(Sender: TObject; const Rect: TRect;
DataCol: Integer; Column: TColumn; State: TGridDrawState);
begin
Pgina 46
Pgina 49
Pgina 50
Pgina 51
Pgina 55
Pgina 57
Pgina 63