Você está na página 1de 25

{-------------------------------------------------------------------------------

Deel Sistemas
--------------------------------------------------------------------------------
Projeto.........: Sistema de emisso de carteira estudantil (Laercio)
Modulo..........: Biblio - Funcoes do sistema
Versao..........: 1.0
Compilacao......: xe 7
Ambientes.......: Windows 9X/NT
Ultima alteracao: 25/11/2015
Responsavel.....: Dorfino Pereira Salgado
-------------------------------------------------------------------------------}

unit Biblio;

interface

uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,


Db, StdCtrls, Mask, DBCtrls, ComCtrls, Buttons, ExtCtrls, Menus, Grids,
variants, WinSock, DateUtils;

type
PString=^TString;
TString=type AnsiString;
EInvalidPeriod = Class(Exception);

{funcao para validar cpf}


function cpf(num: string): boolean;
{funcao para valida cgc}
function cgc(num: string): boolean;
{funcao para criptografar senhas}
function cripta (ssenha:string):string;
{funcao para retornar o proximo codigo de uma tabela}
function RetiraAcento(str: String): String;
{Preenche string no tamanho solicitado}
function REPLICATE (Caracter: String; Tamanho: Integer): String;
{Centraliza uma string no espaco desejado}
function AlinhaCentro(const S: string; const Len: integer; const Ch: Char): string;
{Alinha uma string a Esquerda no espaco desejado}
function AlinhaEsquerda(const S: string; const Len: integer; const Ch: Char):
string;
{Alinha uma string a Direita no espaco desejado}
function AlinhaDireita(texto: string; const Len: integer): string;
{Replica um caractere n vezes formando uma string }
function ReplChar(const Ch: Char; const Len: integer): string;
{Converte Hora para Minutos (usando como base para minutos 60)}
function NumLinhasArq(Arqtexto:String): integer;
{Criptografa uma string}
function Criptografia(mStr, mChave: string): string;
{Retorna verdadeiro se o dia de trabalho do funcionario passou para outro dia}
function VeData(DataAnterior: TDate; HoraAnterior: TTime; DataAtual: TDate;
HoraAtual: TTime): Boolean;
{Retorna minutos em hora}
function MinutoEmHora(Minuto: Integer): TTime;
{Verifica se a empresa foi selecionada}
function VerEmpresa(cod_emp: integer): boolean;
{Retorna a versao do projeto}
function GetBuildInfo:string;
{Retorna a data e hora do executavel}
function PegaDataHoraExe(TheFileName: string; Valor: string = ''): string;
{Remove numeros ou letras de uma string}
function RemoveNumeroLetra( sTexto: string; Numeros:Boolean ): string;
{Valida hora para nao ser informado 0(zero hora) qdo usado objeto}
function ValidaHora(Retorno: TComponent): Boolean;
(*valida hora (string)*)
function VerificaHora(Hora: string): boolean;
(*valida data*)
function ValidaData(Data: String): Boolean;
{retira o caracter ASCII da string}
function RemoveEnter( sTexto:String ):String;
{criptografia}
function Encrypt( Senha: string ): string;
//formata o texto no tamanho desejado
function FormatarTexto(STEXTO:String; TAMANHO:Integer):String;
(*retorna parte de uma string pegando como parametro um separador definido*)
function PegaCampo(sTexto,sSeparador: String; var iPos: Integer):String;
(*funcao para criptografar strings*)
function Crypt(Action, Src: String): String;
(*funcao inputbox com curinga para senha*)
function SenhaInputBox(const ACaption, APrompt:string): string;
(*retorna o tamanho de um arquivo texto*)
function TamanhoArquivo(ARQUIVO: string): Integer;
(*valida se o valor numero*)
function ValidaTxtNum(Valor: string): Boolean;
{Habilita e desabilita botoes}
procedure HabilitaBotoes( Form:TForm; Status:Boolean );
procedure HabilitaBtn(Form:TForm; Status:Boolean);
{Limpa todos os edits do formulario especificado}
procedure LimpaEdit (Form: TForm);
{Arredondamento de numero para uma quantidade casas decimais ------------------}
function Arredondar(Valor: Double; CasasDecimais: Integer = 2): Double;
{Gravar fisicamente os dados no banco de dados --------------------------------}
procedure GravaSemAcentos(DataSet:TDataSet);
{Manipular cursor do mouse ----------------------------------------------------}
function MouseShowCursor(const Show: boolean): boolean;
{Conta carateres numa string e retorna o numero inteiro -----------------------}
function ContaCaracteres(pTexto:String):Integer;
{Calcula a idade exata --------------------------------------------------------}
function Idade(pDataNasc : TDate) : String;
Function DiasDoMes(AYear, AMonth: Integer): Integer;
Function Bissexto(AYear: Integer): Boolean;
Function Date_Diff(Period: Word; Date2, Date1: TDatetime):Longint;
{Limpar a barra de Status -----------------------------------------------------}
Procedure LimpaBarra(pStatusBarr:TStatusBar);
{Grava o usario/data atuais ---------------------------------------------------}
Procedure GravaUsuario(pDataSet: TDataSet; pUsuario:String);
// MASCARA DE TELEFONE
function MascaraTelefone(Edt:TDBEdit):TDBEdit;
//MASCARA CPF TDBEDIT
function MascaraCPF(Edt:TDBEdit):TDBEdit;
//MASCARA CPF TEDIT
function MascaraCPFTEDIT(Edt:TEdit):TEdit;
//VALIDA CPF VLADMIR
Function testacpf(cpf:string):boolean;
//Serial Busca serial do HD
Function SerialHD(FDrive:String) :String;

implementation
uses UDMDados;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

Procedure GravaUsuario(pDataSet: TDataSet; pUsuario:String);


begin
if (pDataSet.State=dsInsert) then
begin
pDataSet.FieldByName('DATA_INC').AsDateTime:=Now;
pDataSet.FieldByName('USUARIO_INC').Value:=pUsuario;
end
else
begin
pDataSet.FieldByName('USUARIO_ALT').Value:=pUsuario;
pDataSet.FieldByName('DATA_ALT').AsDateTime:=Now;
end;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

Procedure LimpaBarra(pStatusBarr:TStatusBar);
begin
with pStatusBarr do
begin
Panels[1].Text:=EmptyStr;
Panels[2].Text:=EmptyStr;
Panels[4].Text:=EmptyStr;
Panels[5].Text:=EmptyStr;
end;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

Function Date_Diff(Period: Word; Date2, Date1: TDatetime):Longint;


Var
Year, Month, Day, Hour, Min, Sec, MSec: Word; //These are for Date 1
Year1, Month1, Day1, Hour1, Min1, Sec1, MSec1: Word; //these are for Date 2
Begin
//Decode Dates Before Starting
//This is probably ineficient but it will save doing it for each
//different Period.
DecodeDate(Date1, Year, Month, Day);
DecodeDate(Date2, Year1, Month1, Day1);
DecodeTime(Date1, Hour, Min, Sec, MSec);
DecodeTime(Date2, Hour1, Min1, Sec1, MSec1);

//Default Return will be 0


Result := 0;

//Once Decoded Select Type of DateDiff To Return via Period Parameter


Case Period of
1: //Seconds
Begin
//first work out days then * days by 86400 (mins in day)
//Then minus the difference in hours * 3600
//then minus the difference in minutes * 60
//Then get the difference in seconds
Result := (((((Trunc(Date1) - Trunc(Date2))* 86400) - ((Hour1 -
Hour)* 3600))) - ((Min1 - Min) * 60)) - (Sec1 - Sec);
end;
2: //Minutes
Begin
//first work out days then * days by 1440 (mins in day)
//Then minus the difference in hours * 60
//then minus the difference in minutes
Result := (((Trunc(Date1) - Trunc(Date2))* 1440) - ((Hour1 - Hour)*
60)) - (Min1 - Min);
End;
3: //hours
Begin
//First work out in days then * days by 24 to get hours
//then clculate diff in Hours1 and Hours
Result := ((Trunc(Date1) - Trunc(Date2))* 24) - (Hour1 - Hour);
End;
4: //Days
Begin
//Trunc the two dates and return the difference
Day1:=Trunc(Date1) - Trunc(Date2);
Result:=Trunc(Date1) - Trunc(Date2);
End;
5: //Weeks
Begin
//Trunc the two dates and divide
//result by seven for weeks
Result := (Trunc(Date1) - Trunc(Date2)) div 7;
end;
6: //Months
Begin
//Take Diff in Years and * 12 then add diff in months
Result := ((Year - Year1) * 12) + (Month - Month1);
End;
7: //Years
Begin
//Take Difference In Years and Return result
Result := Year - Year1;
End
Else //Invalid Period *** Raise Exception ***
Begin
Raise EInvalidPeriod.Create('Invalid Period Assigned To DateDiff');
Result := 0;
end;
End;
End;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

Function Bissexto(AYear: Integer): Boolean;


begin
Result:=(AYear mod 4=0) and ((AYear mod 100<>0) or (AYear mod 400=0));
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

Function DiasDoMes(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 Bissexto(AYear) then
Inc(Result);
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function Idade(pDataNasc : TDate) : String;


Var Ano1, Mes1, Dia1, Ano2, Mes2, Dia2, Ano, Mes, Dia : Word;
Idade : String;
AuxDia1, AuxDia2 : Integer;
begin
Idade:=EmptyStr;
if (pDataNasc=0) then
begin
Result:=Idade;
Exit;
end;

DecodeDate(pDataNasc, Ano1, Mes1, Dia1);


DecodeDate(Date, Ano2, Mes2, Dia2);
AuxDia1:=Dia1;
AuxDia2:=Dia2;

if (Dia1>Dia2) And ((Mes2-Mes1)=1) then


begin
Dia2:=Dia2+DiasDoMes(Ano1,Mes1);
Mes1:=Mes2;
end
else if (Dia1>Dia2) And (Mes1<>Mes2) then
begin
Dia2:=Dia2+DiasDoMes(Ano1,Mes1);
end
else
if (Mes1=Mes2) And (Dia1>Dia2) And (Ano1<>Ano2) then
begin
Dia2:=Dia2+DiasDoMes(Ano1,Mes1);
Mes2:=Mes2+11;
Ano1:=Ano1+1;
end;

if (Mes1>Mes2) And (AuxDia1<=AuxDia2) then


begin
Ano1:=Ano1+1;
Mes2:=Mes2+12;
end
else if (Mes1>Mes2) And (AuxDia1>AuxDia2) then
begin
Ano1:=Ano1+1;
Mes2:=Mes2+11;
end;

Ano:=Ano2-Ano1;
Mes:=Mes2-Mes1;
Dia:=Dia2-Dia1;

if (Ano > 1) then


Idade:=IntToStr(Ano)+' a ' // ' Anos'
else if (Ano=1) then
Idade:=IntToStr(Ano)+' a ' ; // ' Ano';
if (Mes>1) then
Idade:=Idade+', '+IntToStr(Mes)+'m' // ' Meses '
else if (Mes<>0) then
Idade:=Idade+', '+IntToStr(Mes)+'m' ; // ' Ms ';

if (Ano=0) then
Delete(Idade,1,1);

if (Dia>1) then
Idade:=Idade+' e '+IntToStr(Dia)+' Dias'
else if (Dia<>0) then
Idade:=Idade+' e '+IntToStr(Dia)+' Dia';

if ((Mes=0) And (Ano=0)) then


Delete(Idade,1,3);

if ((Ano1=Ano2) And (Mes1=Mes2) And (Dia1>Dia2)) then


Idade:='0';

Result:=Idade;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function ContaCaracteres(pTexto: String): Integer;


var
I, vTot: Integer;
begin
vTot := 0;

for I := 1 to Length(pTexto) do
Inc(vTot);
Result := vTot;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function MouseShowCursor(const Show: boolean): boolean;


var
I: integer;
begin
I := ShowCursor(LongBool(true));
if Show then
begin
Result := I >= 0;
while I < 0 do
begin
Result := ShowCursor(LongBool(true)) >= 0;
Inc(I);
end;
end
else
begin
Result := I < 0;
while I >= 0 do
begin
Result := ShowCursor(LongBool(false)) < 0;
Dec(I);
end;
end;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function Arredondar(Valor: Double; CasasDecimais: Integer = 2): Double;


var
Valor1, Numero1, Numero2, Numero3: Double;
begin
Valor1 := Exp(Ln(10) * (CasasDecimais + 1));
Numero1 := Int(Valor * Valor1);
Numero2 := (Numero1 / 10);
Numero3 := Round(Numero2);
Result := (Numero3 / (Exp(Ln(10) * CasasDecimais)));
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function cripta (ssenha:string):string;


var I: byte;
saux,schave:string[6];
begin
saux := '';
schave:='DEEL';
for I:= 1 to length(ssenha) do
begin
saux := saux + CHAR(byte(ssenha[I]) xor
byte(schave[I]));
end;
cripta:= saux;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function Cpf(num: string): boolean;


var
n1, n2, n3, n4, n5, n6, n7, n8, n9, d1,d2: Integer;
digitado, calculado: string;
begin
if (Length(num)<11) then
begin
if (Length(num)>0) then
Cpf:=False;
Exit;
end;

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];


Cpf := (calculado = digitado);
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

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
Cgc := false;
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 (n1 = n2) and (n2 = n3) and (n3 = n4) and


(n4 = n5) and (n5 = n6) and (n6 = n7) then
Cgc := False;

Cgc := (calculado = digitado);


end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

procedure HabilitaBtn(Form:TForm; Status:Boolean);


begin
try
TToolButton(Form.FindComponent('btIncluir' )).Visible := Status;
TToolButton(Form.FindComponent('btEditar' )).Visible := false;
TToolButton(Form.FindComponent('btExcluir' )).Visible := not Status;
TToolButton(Form.FindComponent('btGravar' )).Visible := not Status;
TToolButton(Form.FindComponent('btCancelar' )).Visible := not Status;
TToolButton(Form.FindComponent('btFechar' )).Visible := Status;
except
end;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

procedure HabilitaBotoes( Form:TForm; Status:Boolean );


begin
try
TToolButton(Form.FindComponent('btExcluir' )).Visible := not Status;
TToolButton(Form.FindComponent('btGravar' )).Visible := not Status;
TToolButton(Form.FindComponent('btCancelar' )).Visible := not Status;
TToolButton(Form.FindComponent('btFechar' )).Visible := Status;
except
end;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

procedure GravaSemAcentos(DataSet:TDataSet);
var
I: Integer;
begin
for I := 0 to Pred(DataSet.FieldCount) do
begin
if (DataSet.Fields[I].FieldName = 'NOMECOMPUTADOR') or
(DataSet.Fields[I].FieldName = 'CAMINHO_PARAMETRO') or
(DataSet.Fields[I].FieldName = 'CAMINHO') then
Continue;

if (DataSet.Fields[I].DataType = ftString) then


DataSet.Fields[I].AsString := RetiraAcento(DataSet.Fields[i].AsString);
end;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function RetiraAcento(str: String): String;


var
I: Integer;
begin
for I := 1 to Length(str) do
case str[I] of
'': str[I] := 'a';
'': str[I] := 'e';
'': str[I] := 'i';
'': str[I] := 'o';
'': str[I] := 'u';
'': str[I] := 'a';
'': str[I] := 'e';
'': str[I] := 'i';
'': str[I] := 'o';
'': str[I] := 'u';
'': str[I] := 'a';
'': str[I] := 'e';
'': str[I] := 'i';
'': str[I] := 'o';
'': str[I] := 'u';
'': str[I] := 'a';
'': str[I] := 'e';
'': str[I] := 'i';
'': str[I] := 'o';
'': str[I] := 'u';
'': str[I] := 'a';
'': str[I] := 'o';
'': str[I] := 'n';
'': str[I] := 'c';
'': str[I] := 'A';
'': str[I] := 'E';
'': str[I] := 'I';
'': str[I] := 'O';
'': str[I] := 'U';
'': str[i] := 'A';
'': str[I] := 'E';
'': str[I] := 'I';
'': str[I] := 'O';
'': str[I] := 'U';
'': str[I] := 'A';
'': str[I] := 'E';
'': str[I] := 'I';
'': str[I] := 'O';
'': str[I] := 'U';
'': str[I] := 'A';
'': str[I] := 'E';
'': str[I] := 'I';
'': str[I] := 'O';
'': str[I] := 'U';
'': str[I] := 'A';
'': str[I] := 'O';
'': str[I] := 'N';
'': str[I] := 'C';
'': str[I] := 'C';
',': str[I] := ' ';
'': str[I] := 'E';
'': str[I] := 'A';
end;
Result := str;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function REPLICATE(Caracter: String; Tamanho: Integer): String;


var
monta : string;
conta : integer;
begin
monta := '';
for conta := 1 to Tamanho do
monta := monta + Caracter;
Result := monta;
end;
//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function AlinhaCentro(const S: string; const Len: integer; const Ch: Char): string;
var
I, J: Integer;
Pad: String;
Impar: Boolean;
begin
I := Length(S);

if (I < Len) then


begin
J := Len - I;
Impar := J mod 2 = 1;
J := J div 2;
Pad := ReplChar(Ch, J);
Result := Pad + S + Pad;

if (Impar) then
Result := Result + Ch;
end else if (I > Len) then
begin
J := I - Len;
Impar := J mod 2 = 1;
J := J div 2;
Result := S;

Delete(Result, I-J+1, J);


Delete(Result, 1, J);

if (Impar) then
begin
Dec(I, J * 2);
Delete(Result, I, 1);
end;
end else
Result := S;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function AlinhaEsquerda(const S: string; const Len: integer; const Ch: Char):


string;
var
LenS: integer;
begin
LenS := Length(S);

if (LenS < Len) then


Result := ReplChar(Ch, Len - LenS) + S
else if (LenS > Len) then
Result := Copy(S, LenS-Len+1, Len)
else
Result := S;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
function AlinhaDireita(texto: string; const Len: integer): string;
var
LenS: Integer;
spaco: string;
I: Integer;
begin
LenS := Length(texto);
if (LenS < Len) then
for I := 1 to Length(texto) do
spaco := spaco + ' ';

Result := spaco + texto;


end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function ReplChar(const Ch: Char; const Len: integer): string;


var
I: Integer;
begin
SetLength(Result, Len);
for I := 1 to Len do
Result[I] := Ch;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function NumLinhasArq(Arqtexto:String): integer;


// Retorna o nmero de linhas que um arquivo possui
var
f: Textfile;
cont:integer;
begin
cont := 0;
AssignFile(f,Arqtexto);
Reset(f);

while not eof(f) Do


begin
ReadLn(f);
Cont := Cont + 1;
end;

Closefile(f);
result := cont;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function Criptografia(mStr, mChave: string): string;


var
I, TamanhoString, pos, PosLetra, TamanhoChave: Integer;
begin
Result:=mStr;
TamanhoString:=Length(mStr);
TamanhoChave:=Length(mChave);

for I:=1 to TamanhoString do


begin
pos:=(i mod TamanhoChave);

if (pos=0) then
pos:=TamanhoChave;

posLetra:=ord(Result[I]) xor ord(mChave[pos]);

if (posLetra=0) then
posLetra:=ord(Result[I]);

Result[I]:=chr(posLetra);
end;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

procedure LimpaEdit (Form: TForm);


var
I:Integer;
begin
for I:=0 to Pred(Form.ComponentCount) do
begin
if (Form.Components[I] is TCustomEdit) then
try (Form.Components[I] as TCustomEdit).Clear; except end;
end;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

{Retorna verdadeiro se o dia de trabalho do funcionario passou para outro dia}


function VeData(DataAnterior: TDate; HoraAnterior: TTime; DataAtual: TDate;
HoraAtual: TTime): Boolean;
begin
if DataAtual > DataAnterior then
Result := True
else if HoraAtual > HoraAnterior then
Result := True
else Result := False;
end;

{converte minutos em hora}


function MinutoEmHora(Minuto: Integer): TTime;
var Nhora: double;
Phora: integer;
Pmin: double;
begin

Nhora := Minuto / 60;


Phora := Trunc(Nhora);
Pmin := round((Nhora - Phora) * 60);

Result := StrToTime(FormatFloat('00',Phora) + ':' + FormatFloat('00',Pmin));


end;

{Retorna a versao do projeto}


function GetBuildInfo:string;
var VerInfoSize: DWORD;
VerInfo: Pointer;
VerValueSize: DWORD;
VerValue: PVSFixedFileInfo;
Dummy: DWORD;
V1, V2, V3, V4: Word;
Prog : string;
begin
Prog := Application.Exename;
VerInfoSize := GetFileVersionInfoSize(PChar(prog), Dummy);
GetMem(VerInfo, VerInfoSize);
GetFileVersionInfo(PChar(prog), 0, VerInfoSize, VerInfo);
VerQueryValue(VerInfo, '', Pointer(VerValue), VerValueSize);
with VerValue^ do
begin
V1 := dwFileVersionMS shr 16;
V2 := dwFileVersionMS and $FFFF;
V3 := dwFileVersionLS shr 16;
V4 := dwFileVersionLS and $FFFF;
end;
FreeMem(VerInfo, VerInfoSize);
result := IntToStr (v1) + '.' +
IntToStr (v2) + '.' +
IntToStr (v3) + '.' +
IntToStr (v4);

//result := Copy (IntToStr (100 + v1), 3, 2) + '.' +


//Copy (IntToStr (100 + v2), 3, 2) + '.' +
//Copy (IntToStr (100 + v3), 3, 2) + '.' +
//Copy (IntToStr (100 + v4), 3, 2);
end;

{Verifica se a empresa foi selecionada}


function VerEmpresa(cod_emp: integer): boolean;
begin
Result := True;
if cod_emp <= 0 then
begin
Application.MessageBox('Nenhuma empresa foi selecionada. Verifique !!!',
'Ateno', MB_OK + MB_ICONINFORMATION);
Result := False;
end;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function PegaDataHoraExe(TheFileName: string; Valor: string = ''): string;


var
FHandle: integer;
begin
Valor := UpperCase(Valor);
FHandle := FileOpen( TheFileName, fmShareDenyNone );

if (Valor = UpperCase('data')) then


Result := DateToStr((FileDateToDateTime(FileGetDate(FHandle))))
else if (Valor = UpperCase('hora')) then
Result := TimeToStr((FileDateToDateTime(FileGetDate(FHandle))))
else begin
Result := DateToStr((FileDateToDateTime(FileGetDate(FHandle)))) + ' ' +
FormatDateTime('hh:mm',
((FileDateToDateTime(FileGetDate(FHandle)))));
end;
FileClose( FHandle );
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function RemoveNumeroLetra( sTexto: string; Numeros:Boolean ): string;


var
x:Integer;
begin
x := 1;
while x <= Length( sTexto ) do
begin
if Numeros then
begin
if not ( sTexto[x] in ['0'..'9'] ) then
Delete( sTexto, x, 1 )
else
Inc(x);
end
else
begin
if ( not ( sTexto[x] in ['a'..'z'] ) ) then
begin
if ( not ( sTexto[x] in ['A'..'Z'] ) ) then
begin
if ( not ( sTexto[x] in ['0'..'9'] ) ) then
begin
if ( sTexto[x] <> ' ' ) then
begin
Delete( sTexto, x, 1 );
end;
end;
end;
end;

Inc(x);
end;
end;
RemoveNumeroLetra := sTexto;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function ValidaHora(Retorno: TComponent): Boolean;


var HoraHora: TTime;
begin
Result := True;
if (Retorno) is (TCustomEdit) then
begin
if (TCustomEdit(Retorno).Text <> '') and (TCustomEdit(Retorno).Text <>
'__:__') then
begin
try
HoraHora := StrToTime(TCustomEdit(Retorno).Text);
except
Application.MessageBox('Hora invlida. Verifique !!!', 'Ateno', MB_OK
+ MB_ICONINFORMATION);
TCustomEdit(Retorno).SetFocus;
Result := False;
end;
if HoraHora = 0 then
begin
TCustomEdit(Retorno).Text := '00:01';
ValidaHora(Retorno);
end;
end;
end
else if (Retorno) is (TField) then
begin
if (TField(Retorno).Text <> '') and (TField(Retorno).Text <> '__:__') then
begin
try
if Length( TField(Retorno).Text ) = 1 then
HoraHora := StrToTime('00:0'+TField(Retorno).Text)
else if Length( TField(Retorno).Text ) = 2 then
HoraHora := StrToTime('00:'+TField(Retorno).Text)
else if Length( TField(Retorno).Text ) = 3 then
HoraHora :=
StrToTime('0'+Copy(TField(Retorno).Text,1,1)+':'+Copy(TField(Retorno).Text,2,1))
else if Length( TField(Retorno).Text ) = 4 then
HoraHora :=
StrToTime(Copy(TField(Retorno).Text,1,2)+':'+Copy(TField(Retorno).Text,3,2))
else
HoraHora := StrToTime(TField(Retorno).Text);

except
TField(Retorno).FocusControl;
Application.MessageBox('Hora invlida. Verifique !!!', 'Ateno', MB_OK
+ MB_ICONINFORMATION);
Result := False;
end;
if HoraHora = 0 then
begin
TField(Retorno).Text := '00:01';
ValidaHora(Retorno);
end;
end;
end;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function MinutoHoraTexto(Minuto: double): String;


var
Nhora: double;
Phora: integer;
Pmin: double;
begin

Nhora := Abs(Minuto) / 60;


Phora := Trunc(Nhora);
Pmin := round((Nhora - Phora) * 60);
if Phora > 99 then
Result := FormatFloat('000', Phora) + ':' + FormatFloat('00', Pmin)
else
begin
if pHora + pMin > 0 then
Result := FormatFloat(' 00', Phora) + ':' + FormatFloat('00', Pmin)
else
Result := '';
end;
end;

//dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

function Encrypt( Senha: string ): string;


Const
Chave: string = 'Jesus';
var
x,y: Integer;
NovaSenha: string;
begin
for x := 1 to Length( Chave ) do
begin
NovaSenha := '';
for y := 1 to Length( Senha ) do
NovaSenha := NovaSenha + chr( (Ord(Chave[x]) xor Ord(Senha[y])));
Senha := NovaSenha;
end;
Result := Senha;
end;

function RemoveEnter( sTexto:String ):String;


var
x:Integer;
begin
x := 1;
while x <= Length( sTexto ) do
begin
if ( Ord( sTexto[x] ) = 13 ) or ( Ord( sTexto[x] ) = 10 ) then
Delete( sTexto, x, 1 )
else
Inc(x);
end;
RemoveEnter := sTexto;
end;

//formata o texto no tamanho desejado


function FormatarTexto(STEXTO:String; TAMANHO:Integer):String;
begin
FormatarTexto := Copy(STEXTO, 1, Tamanho) + StringOfChar(' ',TAMANHO -
Length(STEXTO));
end;

function PegaCampo(sTexto,sSeparador: String; var iPos: Integer):String;


var
X: Integer;
sRETORNO: String;
begin
sRETORNO := '';
if SSeparador = '' then SSeparador := ';';
for X := iPos to Length(sTexto) do
if sTexto[X] <> sSeparador then
sRETORNO := Concat(sRETORNO, sTexto[X])
else
begin
iPos := X+1;
Break;
end;
PegaCampo := sRETORNO;
end;

function ValidaData(Data: string): Boolean;


begin
Result := True;
try
StrToDate(Data);
except
Result := False;
end;
end;

function VerificaHora(Hora: string): boolean;


begin
Result := True;
try
StrToTime(Hora);
except
Result := False;
end;
end;
(*funcao para criptografar strings*)
function Crypt(Action, Src: String): String;
Label Fim;
var
KeyLen, KeyPos, OffSet, SrcPos, SrcAsc, TmpSrcAsc, Range : Integer;
Dest, Key : String;
begin

if (Src = EmptyStr) Then


begin
Result:= '';
Goto Fim;
end;

Key :=
'YUQL23KL23DF90WI5E1JAS467NMCXXL6JAOAUWWMCL0AOMM4A4VZYW9KHJUI2347EJHJKDF3424SKL
K3LAKDJSL9RTIKJ';
Dest := '';
KeyLen := Length(Key);
KeyPos := 0;
SrcPos := 0;
SrcAsc := 0;
Range := 256;

if (Action = UpperCase('C')) then


begin
Randomize;
OffSet := Random(Range);
Dest := Format('%1.2x',[OffSet]);

for SrcPos := 1 to Length(Src) do


begin
Application.ProcessMessages;
SrcAsc := (Ord(Src[SrcPos]) + OffSet) Mod 255;
if (KeyPos < KeyLen) then
Inc(KeyPos)
else
KeyPos := 1;

SrcAsc := SrcAsc Xor Ord(Key[KeyPos]);


Dest := Dest + Format('%1.2x',[SrcAsc]);
OffSet := SrcAsc;
end;
end
else if (Action = UpperCase('D')) then
begin
OffSet := StrToInt('$'+ copy(Src,1,2));
SrcPos := 3;

repeat
SrcAsc := StrToInt('$'+ copy(Src,SrcPos,2));

if (KeyPos < KeyLen) then


Inc(KeyPos)
else
KeyPos := 1;

TmpSrcAsc := SrcAsc Xor Ord(Key[KeyPos]);

if (TmpSrcAsc <= OffSet) then


TmpSrcAsc := 255 + TmpSrcAsc - OffSet
else
TmpSrcAsc := TmpSrcAsc - OffSet;

Dest := Dest + Chr(TmpSrcAsc);


OffSet := SrcAsc;
SrcPos := SrcPos + 2;
until
(SrcPos >= Length(Src));
end;

Result:= Dest;
Fim:
end;

function SenhaInputBox(const ACaption, APrompt:string): string;


var
Form: TForm;
Prompt: TLabel;
Edit: TEdit;
DialogUnits: TPoint;
ButtonTop, ButtonWidth, ButtonHeight: Integer;
Value: string;
I: Integer;
Buffer: array[0..51] of Char;
begin
Result := '';
Form := TForm.Create(Application);
with Form do
begin
try
Canvas.Font := Font;
for I := 0 to 25 do Buffer[I] := Chr(I + Ord('A'));
for I := 0 to 25 do Buffer[I + 26] := Chr(I + Ord('a'));
GetTextExtentPoint(Canvas.Handle, Buffer, 52, TSize(DialogUnits));
DialogUnits.X := DialogUnits.X div 52;
BorderStyle := bsDialog;
Caption := ACaption;
ClientWidth := MulDiv(180, DialogUnits.X, 4);
ClientHeight := MulDiv(63, DialogUnits.Y, 8);
Position := poScreenCenter;
Prompt := TLabel.Create(Form);
with Prompt do
begin
Parent := Form;
AutoSize := True;
Left := MulDiv(8, DialogUnits.X, 4);
Top := MulDiv(8, DialogUnits.Y, 8);
Caption := APrompt;
end;
Edit := TEdit.Create(Form);
with Edit do
begin
Parent := Form;
Left := Prompt.Left;
Top := MulDiv(19, DialogUnits.Y, 8);
Width := MulDiv(164, DialogUnits.X, 4);
MaxLength := 255;
PasswordChar := '*';
SelectAll;
end;
ButtonTop := MulDiv(41, DialogUnits.Y, 8);
ButtonWidth := MulDiv(50, DialogUnits.X, 4);
ButtonHeight := MulDiv(14, DialogUnits.Y, 8);
with TButton.Create(Form) do
begin
Parent := Form;
Caption := 'OK';
ModalResult := mrOk;
Default := True;
SetBounds(MulDiv(38, DialogUnits.X, 4),ButtonTop,
ButtonWidth,ButtonHeight);
end;
with TButton.Create(Form) do
begin
Parent := Form;
Caption := 'Cancela';
ModalResult := mrCancel;
Cancel := True;
SetBounds(MulDiv(92, DialogUnits.X, 4),ButtonTop,
ButtonWidth,ButtonHeight);
end;
if ShowModal = mrOk then
begin
Value := Edit.Text;
Result := Value;
end
else
Result := '';
finally
Form.Free;
Form:=nil;
end;
end;
end;

function TamanhoArquivo(ARQUIVO: string): Integer;


begin
if FileExists(ARQUIVO) then
begin
with TFileStream.Create(Arquivo, fmOpenRead or fmShareExclusive) do
try
Result := Size;
finally
Free;
end;
end;
end;

function ValidaTxtNum(Valor: string): Boolean;


begin
Result := True;
try
StrToFloat(Valor);
except
Result := false;
end;
end;

function DataBetween(Data, DATAI, DATAF: TDate): Boolean;


var VAR_DATA, VAR_DATAI, VAR_DATAF: integer;
begin
Result := False;
VAR_DATA := StrToInt(FormatDateTime('YY', DATA) + FormatFloat('00',
MonthOf(DATA)) + FormatFloat('00', DayOf(DATA)));
VAR_DATAI := StrToInt(FormatDateTime('YY', DATAI) + FormatFloat('00',
MonthOf(DATAI)) + FormatFloat('00', DayOf(DATAI)));
VAR_DATAF := StrToInt(FormatDateTime('YY', DATAF) + FormatFloat('00',
MonthOf(DATAF)) + FormatFloat('00', DayOf(DATAF)));
if (VAR_DATA in [VAR_DATAI, VAR_DATAF]) then
Result := True;
end;
{
case ERR of
ERROR_ACCESS_DENIED 0005 : ShowMessage ( 'Acesso negado.' );
ERROR_ALREADY_ASSIGNED 0085 : ShowMessage ( 'A letra do drive
especificada j est conectada.' );
ERROR_BAD_DEV_TYPE 0066 : ShowMessage ( 'O tipo de dispositivo
e o tipo de recurso no so compatveis.' );
ERROR_BAD_DEVICE 1200 : ShowMessage ( 'Letra invlida.' );
ERROR_BAD_NET_NAME 0067 : ShowMessage ( 'Nome do servidor no
vlido ou no pode ser localizado.' );
ERROR_BAD_PROFILE 1207 : ShowMessage ( 'Formato incorreto de
parmetros.' );
ERROR_CANNOT_OPEN_PROFILE 1205 : ShowMessage ( 'Conexo permanente no
disponvel.' );
ERROR_DEVICE_ALREADY_REMEMBERED 1202 : ShowMessage ( 'Uma entrada para o
dispositivo especificado j est no perfil do usurio.' );
ERROR_EXTENDED_ERROR 1208 : ShowMessage ( 'Erro de rede.' );
ERROR_INVALID_PASSWORD 0086 : ShowMessage ( 'Senha especificada
invlida.' );
ERROR_NO_NET_OR_BAD_PATH 1203 : ShowMessage ( 'A operao no foi
concluda porque a rede no foi inicializada ou caminho invlido.' );
ERROR_NO_NETWORK 1222 : ShowMessage ( 'A rede no est
presente.' );
else if Err > 0 then
ShowMessage (IntToStr(Err));
end;
}

// MASCARA DE TELEFONE
function MascaraTelefone(Edt:TDBEdit):TDBEdit;
begin
if Length(Edt.Text) = 1 then
begin
Edt.Text := '(' + Edt.Text;
Edt.Selstart := Length(Edt.Text);
end;

if Length(Edt.Text) = 3 then
begin
Edt.Text := Edt.Text + ')';
Edt.Selstart := Length(Edt.Text);
end;

if Length(Edt.Text) = 8 then
begin
Edt.Text := Edt.Text + '-';
Edt.Selstart := Length(Edt.Text);
end;

Result:=Edt;
end;

// MASCARA DE CPF
function MascaraCPF(Edt:TDBEdit):TDBEdit;
begin
if Length(Edt.Text) = 3 then
begin
Edt.Text := Edt.Text + '.';
Edt.Selstart := Length(Edt.Text);
end;

if Length(Edt.Text) = 7 then
begin
Edt.Text := Edt.Text + '.';
Edt.Selstart := Length(Edt.Text);
end;

if Length(Edt.Text) = 11 then
begin
Edt.Text := Edt.Text + '-';
Edt.Selstart := Length(Edt.Text);
end;

Result:=Edt;
end;

// MASCARA DE CPF TEDT


function MascaraCPFTEDIT(Edt:TEdit):TEdit;
begin
if Length(Edt.Text) = 3 then
begin
Edt.Text := Edt.Text + '.';
Edt.Selstart := Length(Edt.Text);
end;

if Length(Edt.Text) = 7 then
begin
Edt.Text := Edt.Text + '.';
Edt.Selstart := Length(Edt.Text);
end;

if Length(Edt.Text) = 11 then
begin
Edt.Text := Edt.Text + '-';
Edt.Selstart := Length(Edt.Text);
end;

Result:=Edt;
end;

Function testacpf(cpf:string):boolean;
var i:integer;
Want:char;
Wvalid:boolean;
Wdigit1,Wdigit2:integer;
begin
Wdigit1:=0;
Wdigit2:=0;
Want:=cpf[1];//variavel para testar se o cpf repetido como 111.111.111-11
Delete(cpf,ansipos('.',cpf),1); //retira as mascaras se houver
Delete(cpf,ansipos('.',cpf),1);
Delete(cpf,ansipos('-',cpf),1);

//testar se o cpf repetido como 111.111.111-11


for i:=1 to length(cpf) do
begin
if cpf[i] <> Want then
begin
Wvalid:=true; // se o cpf possui um digito diferente ele passou no
primeiro teste
break
end;
end;
// se o cpf composto por numeros repetido retorna falso
if not Wvalid then
begin
result:=false;
exit;
end;

//executa o calculo para o primeiro verificador


for i:=1 to 9 do
begin
wdigit1:=Wdigit1+(strtoint(cpf[10-i])*(I+1));
end;
Wdigit1:= ((11 - (Wdigit1 mod 11))mod 11) mod 10;
{formula do primeiro verificador
soma=1*2+2*3+3*4.. at 9*10
digito1 = 11 - soma mod 11
se digito > 10 digito1 =0
}

//verifica se o 1 digito confere


if IntToStr(Wdigit1) <> cpf[10] then
begin
result:=false;
exit;
end;

for i:=1 to 10 do
begin
wdigit2:=Wdigit2+(strtoint(cpf[11-i])*(I+1));
end;
Wdigit2:= ((11 - (Wdigit2 mod 11))mod 11) mod 10;
{formula do segundo verificador
soma=1*2+2*3+3*4.. at 10*11
digito1 = 11 - soma mod 11
se digito > 10 digito1 =0
}

// confere o 2 digito verificador


if IntToStr(Wdigit2) <> cpf[11] then
begin
result:=false;
exit;
end;

//se chegar at aqui o cpf valido


result:=true;
end;

//Serial Busca serial do HD


Function SerialHD(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;

end.