-
Notifications
You must be signed in to change notification settings - Fork 0
/
uFuncoes.pas
5385 lines (4967 loc) · 180 KB
/
uFuncoes.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-------------------------------------------------------------------------------
Programa..: uFuncoes
Empresa...: DigiBem
Finalidade: Funções utilizadas pelo sistema
Autor Data Operação Descrição
Antonio Gomes DEZ/2004 Criação
Vanessa MAI/2010 Alteração Funções: NomeUsuario, GetIP, GetMACAdress
Vanessa JUL/2010 Alteração Função: Aguarda_Executar
Vanessa DEZ/2011 Alteração Funções: Elimina_Comandos_MySQL, ValidaLetras, SPC Consultas
Vanessa JAN/2012 Alteração Funçôes: GridInsertRow; Inscricao; Mascara_Inscricao; Converte_Nro_AnoMesDia
Vanessa JUL/2013 Versão 2.50 Alteração function ValidarEmail: validação de e-mail (ex: almox@3bsup.eb.mil.br)
Vanessa OUT/2013 Alteração Funcão: Arrumar Máscara de Telefones devido ausência de DDD
Localiza_Ultima_Pasta
-------------------------------------------------------------------------------}
unit uFuncoes;
interface
Uses
SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms,
Dialogs, Printers, DB, dbctrls, Stdctrls, Math, Variants, Mapi,
ShellAPI, Registry, Windows, Mask, Spin, CheckLst,TlHelp32, Wininet,Commctrl,
Winsock, Grids, NB30;
type
// Retorno da função: Converte_Nro_AnoMesDia(iTempo : Integer) : RDATA - Criação: 18.01.2012 - Converter Número em Anos, Meses e Dias
RDATA = record
RD_DIA : Integer;
RD_MES : Integer;
RD_ANO : Integer;
end;
{ Functions }
Function CemExtenso(StrValor: string): string;
Function ValorExtenso(Valor: extended): string;
function AllTrim(OQue : String) : String;
function PadLeft(StrToPad: String; LenToPad: Integer; StrFill: String) : String;
function PadRight(StrToPad: String; LenToPad: Integer; StrFill: String) : String;
Function Space(Numero : Integer) : string;
function ValidaData(sData : String) : Boolean;
function DiadaSemana(Data : TDateTime) : String;
function DiaSemanaAbrev(Data : TDateTime) : String;
function LetraSemana(Data : TDateTime) : String;
function CompData(sDataIni, sDataFim, sMensagem1, sMensagem2 : String) : Boolean;
function MesExtenso(Data : TDateTime) : string;
function Mes(Data : TDateTime) : string;
function NomeEstado(Sigla : String) : String;
function VerificaEstado(Sigla : String) : Boolean;
function ValidaNum(sNum : String) : Boolean;
function Confirma_Exclusao : Boolean;
function Formata_CPFCGC(Valor, Tipo: String) : string;
function Formata_CEP(CEP : String) : string;
function Formata_CFOP(CFOP: String) : string;
function Formata_Codigo_Produto(PRODUTO: String) : string;
function Substitui_Caracteres(Letras : String) : String;
function Verifica_Caracteres(Letras, TipoPessoa : String) : Boolean;
function Ver_Caracteres(Letras, VerBranco : String) : Boolean;
function Verifica_Historico(Letras, VerBranco : String) : Boolean;
function Elimina_Caracteres(Letras, Elimina, Novo : String) : String;
function Troca_Caracteres(pTexto : String) : String;
function Troca_CaracteresXML(pTexto : String) : String;
function Conta_Domingos(Dia, Mes, Ano : Integer) : Integer;
function Ultimo_Dia(Mes, Ano : Word) : Word;
//=============================================================
function VerificaFloat(sValor:String) : Boolean;
function VerificaVariavel( Variavel : Variant ) : Boolean;
function BiosDate: String;
function CorrentPrinter :String;
function DateMais(Dat:TDateTime;Numdias:Integer): TDateTime;
function JanelaExiste(Classe,Janela:String) :Boolean;
function DelphiCarregado : Boolean;
function DetectaDrv(const drive : char): boolean;
function DiasNoMes(AYear, AMonth: Integer): Integer;
function DifDateUtil(dataini,datafin:string):integer;
function DifHora(Inicio,Fim : String):String;
function DiscoNoDrive(const drive : char): boolean;
function ExisteInt(Texto:String): Boolean;
function GetDefaultPrinterName : string;
function GetMemoryTotalPhys : DWord;
function IdadeAtual(Nasc : TDate): Integer;
function IdadeN(Nascimento:TDateTime) : String;
function isdigit(c:char):boolean;
function IsPrinter : Boolean;
function MemoryReturn(Categoria: integer): integer;
function NumeroSerie(Unidade:PChar):String;
function CPUSpeed: Double;
function NumeroDeCores : Integer;
function Percentdisk(unidade: byte): Integer;
function SystemDateTime(tDate: TDateTime; tTime: TDateTime): Boolean;
function TestaCgc(xCGC: String):Boolean;
function TestaCPF(xCPF: string) : Boolean;
function validapis(Dado : String) : boolean;
function AnoBis(Data: TDateTime): Boolean;
function mod11( cod: string; flg:longint ):string;
function Gera_Digito11( cod: String ) : String;
function Gera_DigFuncionario( cod: String ) : String;
function Gera_Digito_Contrato( cod: String ) : String;
function Gera_Digito_CtaContabil( cod: String ) : String;
function Pergunta(Mensagem,Cabecalho : String) : Boolean;
function PerguntaSim(Mensagem,Cabecalho : String) : Boolean;
function GeraDatas(Data : TDateTime; FatorSoma : Integer ) : TDateTime;
function ValidaHora(sHora :String) : Boolean;
function DifDias(DataVenc:TDateTime; DataAtual:TDateTime): Real;
function Divide(Dividendo, Divisor : Variant): Real;
function Trunca_Numero(Numero : Variant; Decimais : Integer): Real;
function Inteiro(Numero : Variant): String;
function Decimais(Numero : Variant; Decimais : Integer): String;
function Formata_Valor(pValor : Variant; pTamanho, pDecimais : Integer) : String;
function Encripta(const sValor : String) : String;
function Decripta(const sValor : String) : String;
function EnviaEMail(Porta: Integer; Destinatario, Email, Assunto, Body : String; Anexo: PAnsiChar): WordBool; stdcall; export;
function ValidarEmail (Email: String): Boolean;
//function NomeComputador : String;
Function HexToInt(const HexStr: string): longint;
function Digito_Agencia(pBanco : Integer;pAgencia : String) : String;
function Digito_ContaCorrente(pBanco : Integer; pAgencia, pContaCorrente : String) : String;
function Gera_Digito_ChaveAcesso( pChave: String ) : String;
Function RemoveChar(Const Texto:String):String;
function remove_caracter(sString:String):String;
//function Substitui_Caracteres_Oracle(Letras : WideString) : WideString;
function NumLinhasArq(Arqtexto:String): integer;
function Compactar(sComando: string):Boolean;
// Criação: 20/10/2009 - Vanessa Utilidade: Controlar DV na digitação do código do IBGE
function Gera_Digito_IBGE( pCodigo: String ) : String;
// Criação: 06/12/2011 - Vanessa Utilidade: Bloquear para não manipular o banco através dos campos textos do programa
function Elimina_Comandos_MySQL(Texto : WideString) : WideString;
// Criação: 07/12/2011 - Vanessa Utilidade: aceita somente letras
function ValidaLetras(Texto : String) : String;
// Criação: 07/12/2011 - Vanessa Utilidade: Validar Caracteres para consultas SPC
function SPC_Valida_Caracteres(Texto : String) : String;
// Criação: 17.01.2012 - Vanessa Utilidade: insere uma linha num TStringGrid APÓS uma linha escolhida.
function GridInsertRow(StrGrid: TStringGrid; Linha:integer):integer;
// Criação: 17.01.2012 - Validar Inscrição Estadual
Function Inscricao(Inscricao, Estado : String) : Boolean;
Function Mascara_Inscricao(Inscricao, Estado : String) : String;
// Criação: 18.01.2012 - Converter Número em Anos, Meses e Dias
Function Converte_Nro_AnoMesDia(iTempo : Integer) : RDATA;
// Criação: 22.04.2013 - Colocar ponto para separar milhar
Function Formata_Valor_Milhar(sValor : String) : String;
// Criação: 28.05.2013 - Contar ocorrencia de palavras em um texto
Function Conta_Ocorrencias_Texto(wsTexto : WideString; sPalavra : String) : Integer;
// Criação: 06.09.2013 - Localizar última pasta de uma string - para auxiliar quando temos um nome para inicio do nome do arquivo no mesmo string
Function Localiza_Ultima_Pasta(sTexto: String) : String;
// Criação: 08.02.2014 - Cálculo de Diferença entre Duas Datas (DD/MM/AAAA) e Horas (HH:MM), mostrando dias, horas e minutos - Result Formato (DDDDHHMM)
Function DifereDatas_DiaHoraMinuto(pDataCompara, pDataAtual, pHoraCompara, pHoraAtual: String) : String;
// Criação: 11.06.2016 - Separa Cidade e UF
Function Separa_Municipio(sMunicipioUF: String) : String;
// Criação: 11.06.2016 - Separa Cidade e UF
Function Separa_UF(sMunicipioUF: String) : String;
// Criação Cálculo Modulo 11 para Boletos 23.02.2016
function NossoNro_Modulo11(Numero: String): String;
function CodBarras_DV_Modulo11(CodBarras: String): String;
function Modulo_10(Numero:String):String;
{ Procedures }
procedure Adverte(Mensagem,Cabecalho : String);
procedure Informacao(Mensagem,Cabecalho : String);
procedure Ampulheta;
procedure Seta;
procedure Delay(iMSecs: Integer);
procedure Verifica_Data(Campo : TField; sData : String);
procedure Transforma_Hora(var pHora : String; pValor : String; var pHoras : Real; var pMinutos : Real );
procedure Transf_Hora(var pHora : String; pValor : Real; var pHoras : Real; var pMinutos : Real);
procedure Cor_Campo(Sender: TObject;Cor : Double);
procedure ApagaProcessos(sPrograma: string);
procedure Treme_Tela(Formulario : TForm; Sender : TObject);
//procedure CreateToolTips(hWnd: Cardinal);
//procedure AdicionaBalao(hwnd: dword; lpti: PToolInfo; IconType: Integer; Text, Title: PAnsiChar);
function fNextString(Text: string): string;
function fFillStringLeft(sText: string; cChar: char; nLength: integer): string;
function fFillStringRight(sText: string; cChar: char; nLength: integer): string;
function fDateBraUsa(sDateBra :string): string ;
function fAllTrim(sString :string) : string;
function fAllTrimNumeric(sString :string) :string;
function Extenso(Mnum:currency):String;
function fCheckStringDate(sString :string) : Boolean;
function fCheckStringFloat(sString :string) : Boolean;
Function FRetornaMes(Num:String):String;
function fStrReplicate(sChar:String; nLength: integer): string ;
function fStrCol(nPos: integer; sStr: string): string ;
function fStrAlign(sStr: string; nLength:integer; sAlinhamento : string; sFillChar: string): string ;
function StrIsEmpty(sStr: string): boolean ;
function fDecimalToBits(iDecimal : integer): string;
function fStringCurrencyToFloat( sString: String ): Double;
function fStringNumberClear( sString: String ; WithVirgula:integer): String;
function fStringWOPontoOuVirg( sString, tipo: String ): String;
function fExecFile(const sProgram,sDir,sParams:string; nMode:integer):THandle;
function fFindVirgula( sString: String ): integer;
procedure pAjeitaValor(var sString: String ;separador:string );
function fAjeitaValor(sString: String ; separador:string): string;
function fTrocaPontoVirgula(sString: String): string;
function fAjeitaDecimais(Str:String;Dec:integer):String;
function fRetiraVirgula(Str:String):String;
function fArredonda(Valor:real;Separator:char):real;
function fTruncaSe3CasasDecimais(Valor : real):real;
function fTrunca2CasasDecimais(Valor : Currency):Currency;
function fArredonda2CasasDecimais(Valor : Currency):Currency;
function fHextoInt(hexa:char):integer;
function DesTroca_CaracteresXML(pTexto : String) : String;
function Tira_Quebra_Linha(Texto : String) : String;
function fRetiraPonto(Str:string):String;
function ProximaPrestacao (Dia : TDateTime) : TDateTime;
procedure Volta_Cor(Sender : TObject);
procedure Recebe_Cor(Sender : TObject);
function Verifica_internet(var pAcao : String) : boolean;
function NomeArquivo(sCaminho, sSeparador : String): String;
function RetornaUfNFE(Sigla : String) :Integer;
function RetornaUFCodNFe(CodIBGE : Integer) :String;
function Elimina_Um_Caracter(Letras, Elimina, Novo : String) : String;
function TamanhoArquivoKb(Arquivo: string): Double;
function Tira_Quebra_Pag(Texto : String) : String;
function Format_String(sValor: String; iTamanho: integer): String;
// Alteração: 18.09.2013 - Formatar Telefone de acordo com o número de dígitos
function Format_TelefoneDDD(sTelefone : String) : String;
function BuscaMesExtenso(Data : String) :Integer;
function fArredonda3CasasDecimais(Valor : Currency):Currency;
function Formata_CodEstrutural(Valor,Nivel:String) : string;
function FechaPrograma(ExeFileName: string): Integer;
function Decripta_Email(Valor: string): string;
function Encripta_Email(Valor: string): string;
function VerificaCampoConsulta(sProcurar : string) :boolean;
function Maiuscula( St : String) : String;
function Miniscula( St : String) : String;
function GetIP : String;
function GetMACAdress: String;
function NomeUsuario : String;
function Aguarda_Executar(sComando: string):Boolean;
Function Verifica_SoNumero(Texto : String) : String;
//function RetornaValorTag(pXML : WideString; pTagInicial, pTagFinal : String) : String;
function FormataNumero(num: double): string;
function AddDays (const DT: TDateTime; const Days: Extended): TDateTime;
function ProximoDiaUtil (dData : TDateTime) : TDateTime;
function Feriados(dData: TDateTime) : Boolean; // True quando é FERIADO
function Busca_Dia_Util(dData: TDateTime) : TDateTime; // busca uma data válida (dia útil e não feriado)
function Valida_Placa_Veiculo(sPlaca:String): Boolean;
function DataValida(Dt:String):Boolean; stdcall;
// Retorna o número de linhas que um determinado arquivo possui.
function GetNumLinhasArquivoTexto(FileName: String): Integer;
// Separar Telefones na Importação do Gestão (ex: 2 telefones em 1 campo)
function Importa_Telefones(Texto: String) : String;
// Localiza Descrição da Unidade de Medida conforme tabela Unidades
function Descreve_Unidade_Medida(Texto: String) : String;
{ FUNÇÕES AUTOMÁTICAS DO DELPHI
--- Função que arredonde um valor para o próximo inteiro
na uses MATH - função ceil - ex: rArredonda := ceil(rValor);
}
var
resultado : word;
dDatavalida : TDateTime;
dNumValido : Double;
dHoravalida : TTime;
DATA : RDATA;
{hTooltip: Cardinal;
ti: TToolInfo;
buffer : array[0..255] of char;}
//const
// TTS_BALLOON = $40;
// TTM_SETTITLE = (WM_USER + 32);
implementation
//uses // uDtmSisGestao, uFuncoesNFe;
function DataValida(Dt:String):Boolean; stdcall;
var Dia,Mes:Byte;
Ano:Integer;
function AnoBissesto(Year :Integer): boolean ;
begin
AnoBissesto:=(ano mod 4=0) and ( ano mod 100 <> 0) or (ano Mod 400 =0);
end;
begin
Result:=False;
if length(Trim(Dt)) = 10 then
begin
Dia:=StrToIntDef(Copy(Dt,1,2),0);
Mes:=StrToIntDef(Copy(Dt,4,2),0);
Ano:=StrToInt(Copy(Dt,7,4));
if ( (Mes in [1,3,5,7,8,10,12]) and (Dia in [1..31]) ) or
( (Mes in [4,6,9,11]) and (Dia in [1..30]) ) or
( (Mes = 2) and ( AnoBissesto(Ano)) and (Dia in [1..29]) ) or
( (Mes = 2) and (not AnoBissesto(Ano)) and (Dia in [1..28]) ) then
Result:=True;
try
if StrToDate(Dt)< date then
Result:=False;
except
Result:=False;
end;
end;
end;
exports DataValida;
function Maiuscula( St : String) : String;
var
a : Integer;
begin
for a:=1 to Length(St) do
if (St[a]in['a'..'z']) or (St[a]in['à'..'ý']) then
Dec(St[a],32);
Result:=St;
end;
function Miniscula( St : String) : String;
var
a : Integer;
begin
for a:=1 to Length(St) do
if (St[a]in['A'..'Z']) or (St[a]in['À'..'Ý']) then
Inc(St[a],32);
Result:=St;
end;
function NomeUsuario : String;
var
Buffer : array[0..255] of Char;
Size : dword;
UserName: String;
begin
Size := 256;
GetUserName(Buffer, Size);
UserName := Buffer;
Result := UserName;
end;
{function RetornaValorTag(pXML : WideString; pTagInicial, pTagFinal : String) : String;
var
iPosicaoInicial, iPosicaoFinal, iTamanho : Integer;
begin
pXML := UpperCase(pXML);
pTagInicial := UpperCase(pTagInicial);
pTagFinal := UpperCase(pTagFinal);
iPosicaoInicial := Pos(pTagInicial,pXML);
iPosicaoFinal := Pos(pTagFinal,pXML);
iTamanho := Length(pTagInicial);
iPosicaoInicial := iPosicaoInicial + iTamanho;
iTamanho := iPosicaoFinal - iPosicaoInicial;
Result := Copy(pXML,iPosicaoInicial,iTamanho);
end; }
function VerificaCampoConsulta(sProcurar : string) :boolean;
begin
if sProcurar <> '' then
begin
try
Result:=true;
StrToInt(sProcurar);
except
Result:=False;
Informacao('Codigo Invalido!!!','Verifique');
Exit;
end;
end;
end;
function FormataNumero(num: double): string;
var
str : String;
x : Integer;
begin
str := FloatToStr(num);
for x := 1 to length(str) do
if str[x] = ',' then
str[x] := '.';
FormataNumero := str;
end;
function Encripta_Email(Valor: string): string;
var
I, Tamanho: Integer;
NewValue: string;
begin
Tamanho := Length(Valor);
NewValue := Valor;
for I := 0 to Tamanho do
begin
NewValue[I] := Chr(Trunc(Ord(NewValue[I]) * 2));
end;
Result := NewValue;
end;
function Decripta_Email(Valor: string): string;
var
I, Tamanho: Integer;
NewValue: string;
begin
Tamanho := Length(Valor);
NewValue := Valor;
for I := 1 to Tamanho do
begin
NewValue[I] := Chr(Trunc(Ord(NewValue[I]) / 2));
end;
Result := NewValue;
end;
function Formata_CodEstrutural(Valor,Nivel: String) : string;
var iTipo : Integer;
begin
iTipo := StrToInt(Nivel);
case iTipo of
1: Result := Copy(Valor,1,1)+
'. . . . . . ';
2: Result := Copy(Valor,1,1)+'.'+Copy(Valor,2,1)+'.'+
' . . . . ';
3: Result := Copy(Valor,1,1)+'.'+Copy(Valor,2,1)+'.'+
Copy(Valor,3,1)+'.'+
' . . . ';
5: Result := Copy(Valor,1,1)+'.'+Copy(Valor,2,1)+'.'+
Copy(Valor,3,1)+'.'+Copy(Valor,4,2)+'.'+
' . . ';
7: Result := Copy(Valor,1,1)+'.'+Copy(Valor,2,1)+'.'+
Copy(Valor,3,1)+'.'+Copy(Valor,4,2)+'.'+
Copy(Valor,6,2)+'.'+
' . ';
9: Result := Copy(Valor,1,1)+'.'+Copy(Valor,2,1)+'.'+
Copy(Valor,3,1)+'.'+Copy(Valor,4,2)+'.'+
Copy(Valor,6,2)+'.'+Copy(Valor,8,2)+'.'+
' ';
12: Result := Copy(Valor,1,1)+'.'+Copy(Valor,2,1)+'.'+
Copy(Valor,3,1)+'.'+Copy(Valor,4,2)+'.'+
Copy(Valor,6,2)+'.'+Copy(Valor,8,2)+'.'+
Copy(Valor,10,3);
end;
end;
function FechaPrograma(ExeFileName: string): Integer;
const
PROCESS_TERMINATE = $0001;
var
ContinueLoop: BOOL;
FSnapshotHandle: THandle;
FProcessEntry32: TProcessEntry32;
begin
Result := 0;
FSnapshotHandle := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
FProcessEntry32.dwSize := SizeOf(FProcessEntry32);
ContinueLoop := Process32First(FSnapshotHandle, FProcessEntry32);
while Integer(ContinueLoop) <> 0 do
begin
if ((UpperCase(ExtractFileName(FProcessEntry32.szExeFile)) =
UpperCase(ExeFileName)) or (UpperCase(FProcessEntry32.szExeFile) =
UpperCase(ExeFileName))) then
Result := Integer(TerminateProcess(
OpenProcess(PROCESS_TERMINATE,
BOOL(0),
FProcessEntry32.th32ProcessID),
0));
ContinueLoop := Process32Next(FSnapshotHandle, FProcessEntry32);
end;
CloseHandle(FSnapshotHandle);
end;
function fArredonda3CasasDecimais(Valor : Currency):Currency;
begin
Valor := Valor*1000;
Valor := ROUND(Valor);
Valor := (Valor/1000);
fArredonda3CasasDecimais := Valor;
end;
function FormataValor(v: Currency): String;
begin
Result := FormatFloat('#,##0.00', v);
end;
// Mostra Telefone com DDD // Alteração: 18.09.2013 - Formatar Telefone de acordo com o número de dígitos
function Format_TelefoneDDD(sTelefone : String) : String;
var iMascara : Integer;
begin
{
if (Trim(sTelefone) <> '') then
Result := Trim(FormatFloat('(##)####-####',StrToFloat(sTelefone)))
else
Result := '';
}
sTelefone := Verifica_SoNumero(sTelefone);
iMascara := Length(Trim(sTelefone));
Result := '';
case iMascara of
8: Result := Trim(FormatFloat('####-####',StrToFloat(sTelefone)));
9: Result := Trim(FormatFloat('#####-####',StrToFloat(sTelefone)));
10: Result := Trim(FormatFloat('(##)####-####',StrToFloat(sTelefone)));
11: Result := Trim(FormatFloat('(##)#####-####',StrToFloat(sTelefone)));
end;
end;
function Elimina_Um_Caracter(Letras, Elimina, Novo : String) : String;
var
sTrabalho : String;
bTrocou : Boolean;
begin
//sTrabalho := UpperCase(Trim(Letras));
sTrabalho := Trim(Letras);
sTrabalho := StringReplace(sTrabalho,Elimina,Novo,[]);
Result := sTrabalho;
end;
{-----------------------------------------------------------------------------}
{ Função : Copiar o Arquivo em outra pasta }
{-----------------------------------------------------------------------------}
function NomeArquivo(sCaminho, sSeparador : String): String;
var i, Loc : Integer;
begin
Loc := 0;
for i:=0 to Length(sCaminho)-1 do
if Trim(sCaminho[i]) = Trim(sSeparador) then
Loc := i+1;
Result := Copy(sCaminho,Loc,Length(sCaminho));
end;
{testa se a internet esta ativa}
function Verifica_internet(var pAcao : String) : boolean;
var
flags: dword;
begin
if not InternetGetConnectedState(@flags, 0) then
begin
ShowMessage( 'Você não está conectado a Internet Consulte seu Administrador de Rede!!!!');
WinExec('C:\Arquivos de programas\Internet Explorer\Iexplore.exe http://www.google.com.br', sw_shownormal);
pAcao:='CANCELAR';
Exit;
end;
end;
// O retorno da função é o tamanho em Kbytes do arquivo
function TamanhoArquivoKb(Arquivo: string): Double;
begin
with TFileStream.Create(Arquivo, fmOpenRead or fmShareExclusive) do
try
Result := Size/1024;
finally
Free;
end;
end;
procedure Volta_Cor(Sender : TObject);
begin
TMaskEdit(Sender).Color := clWhite;
TComboBox(Sender).Color := clWhite;
TEdit(Sender).Color := clWhite;
TSpinEdit(Sender).Color := clWhite;
end;
procedure Recebe_Cor(Sender : TObject);
begin
TMaskEdit(Sender).Color := clInfoBk;
TEdit(Sender).Color := clInfoBk;
TComboBox(Sender).Color := clInfoBk;
TSpinEdit(Sender).Color := clInfoBk;
end;
{ Calculo do digito de acesso da chave da Nota Fiscal Eletronica }
function Gera_Digito_ChaveAcesso( pChave: String ) : String;
var
iIndice, iDigito : Integer;
lSoma : LongInt;
sDigito, sChave : String;
const
aPesos: array[1..43] of integer = (4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2,9,8,7,6,5,4,3,2);
begin
sChave := Trim(pChave);
if Length(sChave) <> 43 then
begin
Informacao('Chave de acesso inválida!!!!','Aviso...');
Result := ' ';
Exit;
end;
LSoma := 0;
for iIndice := 1 to Length(sChave) do
lSoma := lSoma + (StrToInt(Copy(sChave,iIndice,1)) * aPesos[iIndice]);
iDigito := lSoma mod 11;
iDigito := 11 - iDigito;
if iDigito > 9 then
iDigito := 0;
str(iDigito:1,sDigito);
Result := sDigito;
end;
{ Calcula o digito da agência bancária.
Deve ser passado para a função o número da agência com o digito.
pBanco - Número do banco a ser calculado o digito.
pAgencia - Número da agência a ser calculado o digito }
function Digito_Agencia(pBanco : Integer;pAgencia : String) : String;
var
sAgenciaDigito, sAgencia : String;
wIndice, wPesos : Word;
iSoma, iDigito, iResto : Integer;
begin
// Verifica o código do banco...
case pBanco of
27 : begin // Banco do Estado de Santa Catarina S/A - BESC
sAgenciaDigito := PadLeft(Trim(pAgencia),5,'0');
if (Length(sAgenciaDigito) <> 5) then
begin
Result := '-1';
Exit;
end;
// Pega numero da agencia somente....
sAgencia := Copy(sAgenciaDigito,1,4);
iSoma := 0;
for wIndice := 1 to Length(sAgencia) do
begin
wPesos := 6 - wIndice;
iDigito := StrToInt(Copy(sAgencia,wIndice,1));
iSoma := iSoma + (wPesos * iDigito);
end;
// Calcula o resto da divisão por 11...
iResto := (iSoma mod 11);
iDigito := 11 - iResto;
if (iResto in [1,0]) then
iDigito := 0;
Result := IntToStr(iDigito);
end;
else
Result := 'X';
end;
end;
{ Calcula o digito da conta corrente.
Deve ser passado para a função o número da conta com o digito.
pBanco - Número do banco a ser calculado o digito.
pAgencia - Número da agência com o digito verificador.
pContaCorrente - Número da conta corrente com o digito }
function Digito_ContaCorrente(pBanco : Integer; pAgencia, pContaCorrente : String) : String;
const
wPesos : array[1..10] of word = (3,2,9,8,7,6,5,4,3,2);
var
sAgenciaDigito, sAgencia, sContaDigito, sConta, sPesos : String;
wIndice : Word;
wConta : array[1..10] of word;
iSoma, iDigito, iResto : Integer;
begin
// Verifica o código do banco...
case pBanco of
27 : begin // Banco do Estado de Santa Catarina S/A - BESC
sAgenciaDigito := PadLeft(Trim(pAgencia),5,'0');
if (Length(sAgenciaDigito) <> 5) then
begin
Result := '-1'; Exit;
end;
// Pega numero da agencia somente....
sAgencia := Copy(sAgenciaDigito,1,4);
sContaDigito := PadLeft(Trim(pContaCorrente),13,'0');
if (Length(sContaDigito) <> 13) then
begin
Result := '-1'; Exit;
end;
// Pega numero da conta somente....
sConta := Copy(sContaDigito,7,6);
sConta := sAgencia+sConta;
sPesos := '3298765432';
// Calcula o digito da conta corrente...
iSoma := 0;
for wIndice := 1 to Length(sConta) do
iSoma := iSoma + (StrToInt(Copy(sConta,wIndice,1)) * StrToInt(Copy(sPesos,wIndice,1)));
// Calcula o resto da divisão por 11...
iResto := (iSoma mod 11);
iDigito := 11 - iResto;
if (iResto in [1,0]) then
iDigito := 0;
Result := IntToStr(iDigito);
end;
41 : begin // Banco do Estado do Rio Grande do Sul S/A - Banrisul
sContaDigito := PadLeft(Trim(pContaCorrente),10,'0');
if (Length(sContaDigito) <> 10) then
begin
Result := '-1'; Exit;
end;
// Pega numero da conta somente....
sConta := Copy(sContaDigito,1,9);
sPesos := '324765432';
iSoma := 0;
for wIndice := 1 to Length(sConta) do
iSoma := iSoma + (StrToInt(Copy(sConta,wIndice,1)) * StrToInt(Copy(sPesos,wIndice,1)));
// Calcula o resto da divisão por 11...
iResto := (iSoma mod 11);
iDigito := 11 - iResto;
case iResto of
0 : iDigito := 0;
1 : iDigito := 6;
end;
Result := IntToStr(iDigito);
end;
else
Result := 'X';
end;
end;
procedure ApagaProcessos(sPrograma: string);
var
SnapShot:THandle;
pe:TProcessEntry32;
codigo: string;
processo: dword;
C: integer;
begin
SnapShot := CreateToolhelp32Snapshot((TH32CS_SNAPPROCESS or TH32CS_SNAPTHREAD),0);
pe.dwSize := sizeof(TProcessEntry32);
Process32First(SnapShot,pe);
codigo := '';
processo := 0;
// procura todos sPrograma abertos
repeat
if (String(pe.szExeFile) = sPrograma) then
begin
codigo := format('%x',[pe.th32ProcessID]);
// Converte a string em dword
for C:=1 to length(codigo) do
begin
processo := processo shl 4;
if ord(codigo[C]) >= ord('A') then
processo:=processo + (ord(codigo[C])-ord('A')+10)
else
processo:=processo + (ord(codigo[C])-ord('0'));
end;
// fecha o processo
try
TerminateProcess(OpenProcess($0001,false,processo),0); // $0001 = Process_Terminate.
codigo := '';
processo := 0;
except
showmessage('Falha ao encerrar o processo !');
end;
end;
until Process32Next(SnapShot,pe) = false;
end;
// Procedimento para Trocar de Cor do Objeto quando Focado.
procedure Cor_Campo(Sender: TObject;Cor : Double);
begin
TEdit(Sender).Color := StrToInt(FloatToStr(Cor));
TMaskEdit(Sender).Color := StrToInt(FloatToStr(Cor));
TCheckListBox(Sender).Color := StrToInt(FloatToStr(Cor));
TMemo(Sender).Color := StrToInt(FloatToStr(Cor));
TComboBox(Sender).Color := StrToInt(FloatToStr(Cor));
TSpinEdit(Sender).Color := StrToInt(FloatToStr(Cor));
end;
{function NomeComputador : String;
var
lpBuffer : PAnsiChar;
nSize : DWord;
const
Buff_Size = MAX_COMPUTERNAME_LENGTH + 1;
begin
nSize := Buff_Size;
lpBuffer := StrAlloc(Buff_Size);
GetComputerName(lpBuffer,nSize);
Result := String(lpBuffer);
StrDispose(lpBuffer);
end;}
Function HexToInt(const HexStr: string): longint;
var
iNdx: integer;
cTmp: Char;
begin
Result := 0;
for iNdx := 1 to Length(HexStr) do
begin
cTmp := HexStr[iNdx];
case cTmp of
'0'..'9': Result := 16 * Result + (Ord(cTmp) - $30);
'A'..'F': Result := 16 * Result + (Ord(cTmp) - $37);
'a'..'f': Result := 16 * Result + (Ord(cTmp) - $57);
else
raise
EConvertError.Create('Illegal character in hex string');
end;
end;
end;
function EnviaEMail(Porta: Integer; Destinatario, Email, Assunto, Body : String; Anexo: PAnsiChar): WordBool; stdcall; export;
var
MapiMessage: TMapiMessage;
MError: Cardinal;
Sender: TMapiRecipDesc;
PRecip, Recipients: PMapiRecipDesc;
PFiles, Attachments: PMapiFileDesc;
begin
Result := False;
Application.Handle := Porta;
MapiMessage.nRecipCount := 1;
GetMem(Recipients, MapiMessage.nRecipCount * sizeof(TMapiRecipDesc));
try
with MapiMessage do
begin
ulReserved := 0;
lpszSubject := PAnsiChar(Assunto);
lpszNoteText := PAnsiChar(Body);
lpszMessageType := nil;
lpszDateReceived := nil;
lpszConversationID := nil;
flFlags := 0;
Sender.ulReserved := 0;
Sender.ulRecipClass := MAPI_ORIG;
Sender.lpszName := PAnsiChar('');
Sender.lpszAddress := PAnsiChar('');
Sender.ulEIDSize := 0;
Sender.lpEntryID := nil;
lpOriginator := @Sender;
PRecip := Recipients;
PRecip^.ulReserved := 0;
PRecip^.ulRecipClass := MAPI_TO;
PRecip^.lpszName := StrNew(PAnsiChar(Destinatario));
PRecip^.lpszAddress := StrNew(PAnsiChar('SMTP:' + Email));
PRecip^.ulEIDSize := 0;
PRecip^.lpEntryID := nil;
Inc(PRecip);
lpRecips := Recipients;
nFileCount := 1;
GetMem(Attachments, nFileCount * sizeof(TMapiFileDesc));
PFiles := Attachments;
Attachments^.lpszPathName := Anexo;
Attachments^.lpszFileName := PAnsiChar(ExtractFileName(Anexo));
Attachments^.ulReserved := 0;
Attachments^.flFlags := 0;
Attachments^.nPosition := Cardinal(-1);
Attachments^.lpFileType := nil;
Inc(Attachments);
lpFiles := PFiles;
end;
MError := MapiSendMail(0, Porta, MapiMessage, MAPI_DIALOG or
MAPI_LOGON_UI or MAPI_NEW_SESSION, 0);
case MError of
MAPI_E_USER_ABORT: MessageDlg('Operação abortada pelo usuário',
mtInformation, [mbOk], 0);
SUCCESS_SUCCESS: Result := True;
else
MessageDlg('Ocorreu um erro inesperado!'#13 +
'Código: ' + IntToStr(MError), mtError, [mbOk], 0);
end;
finally
PRecip := Recipients;
StrDispose(PRecip^.lpszAddress);
Inc(PRecip);
FreeMem(Recipients, MapiMessage.nRecipCount * sizeof(TMapiRecipDesc));
if Assigned(PFiles) then FreeMem(PFiles, MapiMessage.nFileCount * sizeof
(TMapiFileDesc));
Application.Handle := 0;
end;
end;
function ValidarEmail (Email: String): Boolean;
var
j, tam_email,
qtd_arroba, iPosicaoArroba,
qtd_pontos, qtd_pontos_esq, qtd_pontos_dir,
iPosicaoAposUltimoPonto, ponto, ponto2: Integer;
vet_email, vet_valido: Array [0..49] of String;
msg: String;
begin
msg := '';
Result := True;
qtd_pontos := 0;
qtd_pontos_esq := 0;
qtd_pontos_dir := 0;
qtd_arroba := 0;
iPosicaoArroba := 0;
ponto := 0;
ponto2 := 0;
iPosicaoAposUltimoPonto := 0;
// Tamanho do e-mail para validação
tam_email := Length (Email);
// Verificar se Existe "@" contar quantos e armazenar posição
for j := 0 to tam_email - 1 do
begin
vet_email[j] := Copy (Email, j + 1, 1);
if vet_email[j] = '@' then
begin
inc (qtd_arroba);
iPosicaoArroba := j;
end;
end;
// Verificar primeira posição do E-mail
if ((vet_email[0] = '@') or (vet_email[0] = '.') or (vet_email[0] = '-')) then
begin
Result := False;
msg := 'Erro na validação do E-mail! Primeiro caracter é "'+vet_email[0]+'"' + #10 +'E-mail: '+Email;
end;
// Se não existir arroba o e-mail não será válido
if qtd_arroba < 1 then
begin
Result := False;
msg := 'Erro na validação do E-mail! Não existe "@" no endereço e-mail.' + #10 +'E-mail: '+Email;
end
else
// Se não existir mais de um arroba o e-mail não será válido
if qtd_arroba > 1 then
begin
Result := False;
msg := 'Erro na validação do E-mail! '+IntToStr(qtd_arroba)+' Arroba(s) Encontrado(s)' + #10 +'E-mail: '+Email;
end;
// Verificando parte final do e-mail, se o último caracter é inválido
for j := 0 to tam_email - 1 do
if vet_email[j] = '-' then
if ((vet_email[j - 1] = '.') or (vet_email[j - 1] = '-')) then
begin
Result := False;
msg := 'Erro na validação do E-mail! Último caracter é "'+vet_email[j - 1]+'"' + #10 +'E-mail: '+Email;
end;
// caracter posicionado = j
for j := 0 to tam_email - 1 do
if vet_email[j] = '.' then
begin
inc (qtd_pontos);
iPosicaoAposUltimoPonto := j + 1;
// próximo caracter após o ponto = iPosicaoAposUltimoPonto
if j > iPosicaoArroba then
inc (qtd_pontos_dir)
else
inc (qtd_pontos_esq);
// caracter anterior ao Ponto = iPosicaoAposUltimoPonto
if ((vet_email[j - 1] = '.') or (vet_email[j - 1] = '-')) then
begin
Result := False;
msg := 'Erro na validação do E-mail! Caracter Anterior ao Ponto é "'+vet_email[j - 1]+'"' + #10 +'E-mail: '+Email;
end;
end;
// Se não localizou ponto no endereço de e-mail
if qtd_pontos < 1 then
begin
Result := False;
msg := 'Erro na validação do E-mail! Nenhum PONTO Encontrado.' + #10 +'E-mail: '+Email;
end
else
// SENÃO - se o último caracter for um ponto
if vet_email[tam_email - 1] = '.' then
begin
Result := False;
msg := 'Erro na validação do E-mail! Último caracter é "'+vet_email[tam_email - 1]+'"' + #10 +'E-mail: '+Email;
end
else
// SENÃO - se o penúltimo caracter for um ponto
if vet_email[tam_email - 2] = '.' then
begin
Result := False;
msg := 'Erro na validação do E-mail! Penúltimo caracter é "'+vet_email[tam_email - 2]+'" '+ #10 +'E-mail: '+Email;
end
else
// SENÃO - se a quantidade de pontos for MAIOR que 3
if qtd_pontos_dir > 3 then // qtd_pontos_dir > 2
begin
Result := False;
msg := 'Erro na validação do E-mail! ' + IntToStr (qtd_pontos_dir) + ' "." Encontrados a direita do "@"' + #10 +
'E-mail: '+Email;
end
else
// SENÃO -
if (not(
// nro de caracteres após o último ponto for igual a 3 E a quantidade de pontos a direita for 1
(((tam_email - iPosicaoAposUltimoPonto) = 3) and (qtd_pontos_dir = 1))
or
// nro de caracteres após o último ponto for igual a 2 E a quantidade de pontos a direita for 3
(((tam_email - iPosicaoAposUltimoPonto) = 2) and (qtd_pontos_dir = 3))
or
// nro de caracteres após o último ponto for igual a 2 E a quantidade de pontos a direita for 2
(((tam_email - iPosicaoAposUltimoPonto) = 2) and (qtd_pontos_dir = 2))
or
// nro de caracteres após o último ponto for igual a 2 E a quantidade de pontos a direita for 1
(((tam_email - iPosicaoAposUltimoPonto) = 2) and (qtd_pontos_dir = 1))
)) then
begin
Result := False;
msg := 'Erro na validação do E-mail! ' + #10 +
'Ponto(s) Encontrado(s) a esquerda do "@" : ' + IntToStr (qtd_pontos_esq) + #10 +
'Ponto(s) Encontrado(s) a direita do "@" : ' + IntToStr (qtd_pontos_dir) + #10 +'E-mail: '+Email;;
end;
// Cliente: Anderson Britto
if trim(email) = 'unisysnfesaopaulo@br.unisys.com' then
Result := True;