Correção de BUGs na Lista Telefónica Topic is solved

Tire suas dúvidas sobre programação em AutoHotkey

Moderator: Gio

AFerreira
Posts: 14
Joined: 01 Mar 2017, 07:07

Correção de BUGs na Lista Telefónica

10 Apr 2019, 18:42

Olá,
Tendo em conta que, isto atualmente já é "muita areia para a minha camioneta", agradecia alguém a leitura do código na perspetiva de detetar os erros descritos e sua resolução ou outros erros (ainda não encontrados...):

1) Ao alterar através do menu "Alterar" (por ex 2 cliques numa linha já guardada/gravada), as novas informações aparecem/ficam aparentemente guardadas na Listview mas... desaparecem aquando de uma nova ação (saida do programa, novo registo, etc....);

2) Aquando da inserção/gravação do 10.º registo, este passa para 2.º lugar...ao 20.º para 3.º lugar e assim
sucessivamente...;

3) O eliminar de várias linhas, não funciona correto com o (botão direito), menu editar/eliminar em cima da
ListView. Pois, se existirem várias linhas selecionadas, só elimina uma de cada vez...

4) Se houver uma linha selecionada na Listview, propositada ou acidentalmente e formos de seguida registar uma nova entrada,
ela vai ser guardada "em cima da linha selecionada", o que é muito mau..! A alteração da linha só poderia
ocorrer no menu alterar, ou seja, após click duplo na linha, ou com rightclick + editar
(Este erro acontecia mas, acabei de simular e não parece existir...)
Obrigado

Code: Select all

#warn
Gui,1:default

REPOSITORIO_DE_ORDEM := 1 ; INICIAMOS EM 1
setworkingdir,%a_scriptdir%
F1=%A_scriptdir%\Registo_Contatos.txt
MainWindowTitle=CONTATOS
Creator=A.Ferreir@
Versão=1.0

dlm:=""
total:=6

FormatTime, Portugal, %a_now% L2070, dddd MMMM yyyy-MM-dd
time:=a_hour . ":" a_min
portugal2:= portugal . "   " . time

transform,T,chr,09                  
gosub,testfile

Gui, Add, StatusBar,,Created by %creator%   %versão%     %portugal%
Gui, Color, +BEBEBE ; Cor do backround 2
Gui, Font, s12 cBlack, Tahoma
header1:="ID:| Designação:| Telefone:| Fax:| E-Mail:| Morada:"

Gui, Add, GroupBox, cBlue x12 y5 w1077 h325, Informações:    
Gui, add, ListView, backgroundblack cCDCD00  r5 x20 y25 h296 w1062 gLVa vLV1 +altsubmit, %header1%
Lv_ModifyCol(1, 50),Lv_ModifyCol(2, 220),Lv_ModifyCol(3, 110),Lv_ModifyCol(4, 110),Lv_ModifyCol(5, 220),Lv_ModifyCol(6, 350)  
   gosub,fill
Gui Add, GroupBox, -cBlue x12 y345 w190 h54, Pesquisar dados: 
Gui, Add, Edit,  x21  y366 w172 h28 gFind vSrc,    
Gui Add, GroupBox, -cBlue x215 y345 w240 h54, Eliminar linha (s): 
Gui, Add, Button, x225  y365 w220 h28 gEliminarx, Eliminar selecionados (as)  
Gui Add, GroupBox, -cBlue x468 y345 w200 h54, Imprimir Lista: 
Gui, Add, Button, x480  y365 w180 h28 gPrint2, Imprimir lista  ; Fazer codigo botao IMPRIMIR-----------
Gui Add, GroupBox, -cBlue x12 y402 w820 h140, Registo: 
Gui Add, GroupBox, -cBlue x845 y402 w145 h140,  
Gui, add, Text,  x30 y428, Designação:                  
Gui, Add, Edit,  x25  y450 w300 h28 vNOME,    
Gui, add, text,  x355  y428, Telefone:                         
Gui, add, Edit,  x350  y450 w120 h28 vFONE,   
Gui, Add, text, x500 y428, Fax:
Gui, Add, Edit, vINFORM_COMPL x495 y450 w120 h28 
Gui, Add, text, x30 y482 w100 h20, E-Mail:      
Gui, Add, Edit, x25  y503 w240 h28 vNPP, 
Gui, add, Text,  x300 y482, Morada:                  
Gui, Add, Edit,  x295  y503 w520 h28 vMorada,    ; Variavel morada-------------------
Gui, Add, Button,x858 y420 w120  h30 gAdd , Guardar      
Gui, Add, Button,x858 y460 w120  h30 gLimpa, Limpar  
Gui, Add, Button,x858 y500 w120  h30 gSair2, Sair  
Gui, show, xCenter yCenter w1100 h580, %MainWindowTitle%   
Menu, CMenu, Add, Eliminar, menuDo
Menu, CMenu, Add, Editar , menuDo
Return
; -------------------------------------------
Guiclose:
Sair2:
ExitApp
;--------------------------------------------

;============ case-1 PRINT_WYS ====================
print2:
Gui,1:submit,nohide
   Header =
   Loop, % LV_GetCount( "Col" )         ; Loop for however many columns are in the listview.
     {
     LV_GetText( myHeader, 0, A_INDEX ) ; Get column header.
     Header .= myHeader . "; "           ; Build output data.
     }

;-- check maximal lenght from each column ---
FilePrint=%a_scriptdir%\%MainWindowTitle%.txt ; Nome do ficheiro txt "contatos" para impressão
ifexist,%fileprint%
   filedelete,%fileprint%
ControlGet, Listx, List, , SysListView321,%MainWindowTitle%
dlm:=";" 
total:=6  
e5x:=""                                             ;- <<< maybe add a new delimiter which not exists in column
stringreplace,listx,listx,`t,%dlm%,all
e5x .= header . "`r`n"
e5x .= listx 

tx:=""
loop,%total%
  T%a_index%:=0
loop,%total%
  L%a_index%:=0
	Loop,parse,e5x,`n,`r
     {
	 lr=%a_loopfield%
     if lr=
       continue
	 i=0
	 loop,%total%                           ;- get max lenght from x columns
	    {
		i++
        StringSplit,A,lr,%dlm%
        stringlen,L%i%,A%i%
        if (T%i%<L%i%)
           T%i%:=(L%i%+1)                   ;-maximal lenght columnX+1
		}
	 }
;- x columns
loop,%total%	 
 Tx .= "{:" . T%a_index% . "}" . dlm
stringtrimright,tx,tx,1
loop,%total%
  a%a_index%:=""
lr=
e:=""
e .= " " . portugal2 . "                                      A.Ferreir@`r`n--------------------------------------                                      ----------`r`n`n"

Loop, parse,e5x, `n,`r
 {
 lr=%a_loopfield%
 if lr=
    continue
 a :=StrSplit(lr,dlm )
 e .= Format(tx . "`r`n",a*)
 }
fileappend,%e%,%fileprint%
run,%fileprint% 
e=
a=
e5x=
listx=
return
;=============================================


Add:
Gui, submit, nohide                             
Fileappend,%nome%`;%fone%`;%INFORM_COMPL%;%NPP%;%Morada%`r`n,%f1%   ;- LINHA ATUALIZADA COM AS INFORMACOES COMPLEMENTARES.
gosub,fill
sleep,1500
GuiControl,1:,fone,
GuiControl,1:,nome,
GuiControl,1:,INFORM_COMPL,
GuiControl,1:,NPP, 
GuiControl,1:,Morada, 
Return


;-------------- Fill Listview -----------
Fill:
Gui,1:default
gui,1:listview,LV1
LV_Delete()
i=0
loop,read,%F1%
  {
  LR=%A_loopReadLine%
  if LR=
     continue
   i++
loop,%total%
  C%a_index%:=""
      stringsplit,C,LR,`;,
   LV_Add("",I, c1,c2,c3,c4,c5,c6) ; LINHA TUALIZADA COM O C3 (INFORMACOES COMPLEMENTARES).
  }
LV_ModifyCol(1, "Sort CaseLocale")  
LV_Modify(LV_GetCount(), "Vis")
return
;----------- Listview click on row -------------------------------
LVa:
Gui,1:Submit,nohide
if A_GuiEvent = Normal
  {
  LV_GetText(C2,A_EventInfo,2) 	; LINHAS ATUALIZADAS
  LV_GetText(C3,A_EventInfo,3)  ; LINHAS ATUALIZADAS
  LV_GetText(C4,A_EventInfo,4) 	; LINHAS ATUALIZADAS
  LV_GetText(C5,A_EventInfo,5) 	; LINHAS ATUALIZADAS
  LV_GetText(C6,A_EventInfo,6) 	; LINHAS ATUALIZADAS
  cx=%c2%;%c3%;%c4%;%c5%;%c6%; 			; LINHAS ATUALIZADAS
  RN:=LV_GetNext("C")
  RF:=LV_GetNext("F")
  GC:=LV_GetCount()
  }
  
;----------- Listview Opções Rightclick (Eliminar / Alterar) -----
if A_GuiEvent = Rightclick
  {
  LV_GetText(C2,A_EventInfo,2) ; LINHAS ATUALIZADAS
  LV_GetText(C3,A_EventInfo,3) ; LINHAS ATUALIZADAS
  LV_GetText(C4,A_EventInfo,4) ; LINHAS ATUALIZADAS
  LV_GetText(C5,A_EventInfo,5) ; LINHAS ATUALIZADAS
  LV_GetText(C5,A_EventInfo,6) ; LINHAS ATUALIZADAS
  cx=%c2%;%c3%;%c4%;%c5%;%c6%
  RN:=LV_GetNext("C")
  RF:=LV_GetNext("F")
  GC:=LV_GetCount()
  goto,menux 
  }   
;----------- Listview Opções Doubleclick (Alterar) -----------------
if A_GuiEvent = DoubleClick
goto,editarx
return 
;------------- MENU - When Rightclick on row -----------------------
menux:
MouseGetPos, musX, musY
Menu, CMenu, Show, %musX%,%musY%
return
menudo:
If (A_ThisMenuItem = "Eliminar")
   gosub,Eliminarx2
If (A_ThisMenuItem = "Editar")
   gosub,Editarx
return
;-------------- Limpar Dados dos Campos ----------------------------------------
Limpa:             ; Limpa os dados do campo
Gui, submit, nohide 
GuiControl,1:,fone,
GuiControl,1:,nome,
GuiControl,1:,INFORM_COMPL,
GuiControl,1:,Src,
GuiControl,1:,NPP,
GuiControl,1:,Morada,
return    
;-------------- Eliminar Dados dos Campos ----------------------------------------
Eliminarx2:
Gui,1:default
gui,1:listview,LV1
   if RF=0
      return
   ;LV_GetText(C1, RF, 1)
   LV_GetText(C2, RF, 2)
   LV_GetText(C3, RF, 2)
   LV_GetText(C4, RF, 2)
   LV_GetText(C5, RF, 2)
   LV_GetText(C6, RF, 2)
   CT=%c2%;%C3%;%C4%;%C5%;%C6%; 			 ; LINHA TUALIZADA COM O C3 (INFORMACOES COMPLEMENTARES).
   msgbox, 262180, APAGAR ,Tem a certeza que deseja eliminar a (s) linha (s) selecionada (s)?
   IfMsgBox,No
      Return
   LV_Delete(RF)
      FileRead,AA,%F1%
      Filedelete,%F1%
      StringReplace,BB,AA,%ct%`r`n,,
      Fileappend,%BB%,%F1%
return	  
;--------------- DELETE multiple selected rows --------------
Eliminarx:
C1 =
RF = 0
RFL =
Loop
   {
   RF:=LV_GetNext(RF)
   if RF=0
      break
   RFL = %RF%|%RFL%
   LV_GetText(C1_Temp, RF, 1)
   C1 = %C1%`n%C1_Temp%
  }
if C1 !=
 {
   msgbox, 262180, APAGAR , Tem a certeza que deseja eliminar a (s) linha (s) selecionada (s)? 
   IfMsgBox,No
      Return
   Else
   {
      Loop, parse, RFL, |
       LV_Delete(A_LoopField)
     filedelete,%F1%
     Loop % LV_GetCount()
        {
        BX1=
        BX2=
        BX3=
        BX4=
        BX5=
        BX6=
        LV_GetText(BX2,A_INDEX,2) ; LINHA ATUALIZADA
		LV_GetText(BX3,A_INDEX,3) ; LINHA ATUALIZADA
		LV_GetText(BX4,A_INDEX,4) ; LINHA ATUALIZADA
        LV_GetText(BX5,A_INDEX,5) ; LINHA ATUALIZADA
        LV_GetText(BX6,A_INDEX,6) ; LINHA ATUALIZADA
        Fileappend,%BX2%`;%BX3%`;%BX4%;%BX5%;%BX6%`r`n,%F1%
       }
   }
      C1=
      C2=
      C3=
      C4=
      C5=
      C6=
 }
return
;----------------------------------------------------------------------------------------------------------------------------------------------- Imprimir
Imprimir: 
; Registo_Contatos.txt
return
;--------------- modifica ----------------
Editarx:
Gui,1:submit, nohide ; Manter janela 1
;Gui,3: +Alwaysontop
Gui,3:Color, +8B8B00; Cor do backround Alterar
Gui,3:Font, s12 cBlack, Tahoma
Gui,3:Add, GroupBox, -cWhite x12 y8 w500 h54, Designação: 
Gui,3:Add,Edit, x20 y28 w485 h28 vA32, %C2%
Gui,3:Add, GroupBox, -cWhite x12 y65 w148 h54, Telefone:
Gui,3:Add,Edit , x22 y85 w130 h28 vA31, %C3%
Gui,3:Add, GroupBox, -cWhite x175 y65 w148 h54, Fax:
Gui,3:Add, Edit, x185 y85 w130 h28 vVARIAVEL_DAS_INFORMACOES_COMPLEMENTARES, %C4%
Gui,3:Add, GroupBox, -cWhite x12 y120 w312 h54, E-Mail:      
Gui,3:Add, Edit, x22 y140 w295 h28 vC5, %C5% 
Gui,3:Add, GroupBox, -cWhite x12 y175 w500 h56, Morada: 
Gui,3:Add,Edit , x20 y195 w485 h28 vC6, %C6%
Gui,3:Add, Button, x160 y250 w90 h28 gCancelar, &Cancelar
Gui,3:Add, Button, x260 y250 w90 h28 gALTERAR_A_LISTVIEW, Alterar
Gui,3:Show, xCenter yCenter w520 h320, ALTERAR:
Gui,3:Font, s8 cBlack, Tahoma
Gui,3:Add, StatusBar, , Created by %creator%   %versão%
GuiControl,3:Focus,A31
send,^{end}
return
;-------------
ALTERAR_A_LISTVIEW:
Gui,3: Submit, nohide
Gui,1: Default
Lv_Modify(RN, "Col2", A32)
Lv_Modify(RN, "Col3", A31)
Lv_Modify(RN, "Col4", VARIAVEL_DAS_INFORMACOES_COMPLEMENTARES)
Lv_Modify(RN, "Col5", C5)
Lv_Modify(RN, "Col6", C6)

FileRead, CONTEUDO_ATUAL_DO_ARQUIVO, %A_ScriptDir%\Registo.txt
StringReplace, NOVO_CONTEUDO_DO_ARQUIVO, CONTEUDO_ATUAL_DO_ARQUIVO, %C2%`;%C3%`;%C4%`;%C5%`;%C6%`;%A32%`;%A31%`;%VARIAVEL_DAS_INFORMACOES_COMPLEMENTARES%`;%C5%`;%C6%`;
FileAppend, %NOVO_CONTEUDO_DO_ARQUIVO%, %A_ScriptDir%\Registo_NOVO.txt
FileRead, ARQUIVO_ESCRITO, %A_ScriptDir%\Registo_NOVO.txt
If (ARQUIVO_ESCRITO = NOVO_CONTEUDO_DO_ARQUIVO)
{
FileMove, %A_ScriptDir%\Registo_NOVO.txt, %A_ScriptDir%\Registo.txt, 1
FileRead, CONTEUDO_ATUAL_DO_ARQUIVO, %f1%
If (ErrorLevel)
{
msgbox, 0x10, ERRO: , Houve um erro na gravAção dos dados na alteração do arquivo. Por favor, tente novamente.
Return
}
else
{
msgbox, 0, SUCESSO: , Alteração efetuada com sucesso !
Gui, 3: Destroy
Return
}
}
Else
{
msgbox, 0x10, ERRO: , Houve um erro na gravação dos dados na alteração do arquivo. Por favor, tente novamente.
}
Return
;--------------------------------------------------------------------------
Cancelar:
Gui,3: destroy
return
;-------------------------------------------------------------------------------------------
3GuiClose:
3GuiEscape:
Gui, 3:Destroy
return
3ButtonOK:
Gui,3:submit
if A31=
   {
   Gui,3: Destroy
   return
   }
FileRead, FileContent, %f1%
FileDelete, %f1%
StringReplace, FileContent, FileContent, %C1%`;%C2%, %A31%`;%A32%`;%C5%`;%C6%`;
FileAppend, %FileContent%, %f1%
GoSub,fill
Gui,3:destroy
return
;------------------- SEARCH -------------------------------
Find:
Gui,1: Submit, Nohide
Gui,1:listview, LV1
checkempty:
if (src="")
   {
   settimer,checkempty,off
   goto,fill
   return
   }
settimer,checkempty,1000
LV_Delete()
  loop,read,%f1%
  {
  LR=%A_loopReadLine%
  if SRC<>
     {
     if LR contains %src%
       {
       stringsplit,C,A_LoopReadLine,`;
       LV_Add("",A_INDEX, C1,C2, C3,C4,C5,C6) ; LINHA TUALIZADA COM O C3 (INFORMACOES COMPLEMENTARES).
       }
     }
  else
   continue
   }
LV_Modify(LV_GetCount(), "Vis")
if (SRC="")
  goto,Fill
return
;--------------- create testfile ----------------------
testfile:
ifnotexist,%f1%
{
  e1=
  (Ltrim Join`r`n

  )
FileAppend,%e1%`r`n,%f1%
e1=
}
Return
User avatar
Gio
Posts: 1247
Joined: 30 Sep 2013, 10:54
Location: Brazil

Re: Correção de BUGs na Lista Telefónica

11 Apr 2019, 09:24

Bom dia AFerreira.
1) Ao alterar através do menu "Alterar" (por ex 2 cliques numa linha já guardada/gravada), as novas informações aparecem/ficam aparentemente guardadas na Listview mas... desaparecem aquando de uma nova ação (saida do programa, novo registo, etc....);
Estas linhas da rotina ALTERAR_A_LISTVIEW não estão corretas (a primeira, a segunda e a última abaixo):

Code: Select all

FileRead, CONTEUDO_ATUAL_DO_ARQUIVO, %A_ScriptDir%\Registo.txt
StringReplace, NOVO_CONTEUDO_DO_ARQUIVO, CONTEUDO_ATUAL_DO_ARQUIVO, %C2%`;%C3%`;%C4%`;%C5%`;%C6%`;%A32%`;%A31%`;%VARIAVEL_DAS_INFORMACOES_COMPLEMENTARES%`;%C5%`;%C6%`;
FileAppend, %NOVO_CONTEUDO_DO_ARQUIVO%, %A_ScriptDir%\Registo_NOVO.txt
FileRead, ARQUIVO_ESCRITO, %A_ScriptDir%\Registo_NOVO.txt
If (ARQUIVO_ESCRITO = NOVO_CONTEUDO_DO_ARQUIVO)
{
FileMove, %A_ScriptDir%\Registo_NOVO.txt, %A_ScriptDir%\Registo.txt, 1
Não existe arquivo "Registo.txt", o arquivo de banco de dados se chama Registo_Contatos.txt. Além disso, faltou o quarto parâmetro do comando StringReplace (na verdade, faltou a vírgula que separa o terceiro e o quarto parâmetro, pois as informações do quarto parâmetro já estão escritas).

:arrow: As linhas em questão devem ficar assim para que o código guarde a informação corretamente no arquivo:

Code: Select all

FileRead, CONTEUDO_ATUAL_DO_ARQUIVO, %A_ScriptDir%\Registo_Contatos.txt
StringReplace, NOVO_CONTEUDO_DO_ARQUIVO, CONTEUDO_ATUAL_DO_ARQUIVO, %C2%`;%C3%`;%C4%`;%C5%`;%C6%, %A32%`;%A31%`;%VARIAVEL_DAS_INFORMACOES_COMPLEMENTARES%`;%C5%`;%C6%
FileAppend, %NOVO_CONTEUDO_DO_ARQUIVO%, %A_ScriptDir%\Registo_NOVO.txt
FileRead, ARQUIVO_ESCRITO, %A_ScriptDir%\Registo_NOVO.txt
If (ARQUIVO_ESCRITO = NOVO_CONTEUDO_DO_ARQUIVO)
{
FileMove, %A_ScriptDir%\Registo_NOVO.txt, %A_ScriptDir%\Registo_Contatos.txt, 1
2) Aquando da inserção/gravação do 10.º registo, este passa para 2.º lugar...ao 20.º para 3.º lugar e assim
sucessivamente...;
Na rotina Fill, que roda quando você clica em "Guardar", está uma função LvModifyCol com parâmetro Sort (ou seja, ordenar) baseado na primeira coluna da listview, e no momento esta ordenação está usando apenas a opção CaseLocale. Isso significa que a ordenação da listview está ocorrendo por ordem alfabética (onde 10 é menor que 2), quando pelo que você está dizendo, deveria ocorrer por ordem numérica (onde 10 é maior que 2). Para isso, você deve mudar a opção CaseLocale para Logical (ou adicionar esta opção ao lado daquela).

Dentro da rotina Fill, esta linha:

Code: Select all

LV_ModifyCol(1, "Sort CaseLocale")
:arrow: Deve ser mudada para esta:

Code: Select all

LV_ModifyCol(1, "Sort Logical")
3) O eliminar de várias linhas, não funciona correto com o (botão direito), menu editar/eliminar em cima da
ListView. Pois, se existirem várias linhas selecionadas, só elimina uma de cada vez...
Você programou duas rotinas diferentes para eliminar os registros selecionados (Eliminarx e Eliminarx2). A que está funcionando é somente a que se chama Eliminarx, então porque não fazer o comando do botão direito chamar a mesma rotina?

onde está assim:

Code: Select all

menudo:
If (A_ThisMenuItem = "Eliminar")
   gosub,Eliminarx2
If (A_ThisMenuItem = "Editar")
   gosub,Editarx
return
:arrow: Basta colocar assim:

Code: Select all

menudo:
If (A_ThisMenuItem = "Eliminar")
   gosub,Eliminarx
If (A_ThisMenuItem = "Editar")
   gosub,Editarx
return
4) Se houver uma linha selecionada na Listview, propositada ou acidentalmente e formos de seguida registar uma nova entrada,
ela vai ser guardada "em cima da linha selecionada", o que é muito mau..! A alteração da linha só poderia
ocorrer no menu alterar, ou seja, após click duplo na linha, ou com rightclick + editar
(Este erro acontecia mas, acabei de simular e não parece existir...)
Em um teste que fiz aqui não tive este erro.
AFerreira
Posts: 14
Joined: 01 Mar 2017, 07:07

Re: Correção de BUGs na Lista Telefónica

11 Apr 2019, 18:48

Olá Gio,
Mais uma vez obrigado pela sua ajuda.
Os problemas 2 e 3 estão resolvidos!
O 4.º, como a vc, também ja não me dava o erro que descrevi, o que estranhei, porque estava me acontecendo. Devo ter resolvido e não dei conta.. :shock:

Em relação ao erro 1), eu fiz a alteração no nome do .txt que vc me falou.
Na verdade eu para simplificar a leitura e evitar apagar na pasta de destino, tinha alterado o nome "Registo", para Registo_Contatos e esqueci a alteração em outros.
Contudo, mesmo neste erro e após as alterações que vc me falou, continuo com o mesmo problema...o programa mantém a nova alteração, incluindo se eu fizer "Imprimir Lista", ele assume as alterações novas mas...basta fazer uma outra ação nova, em algum botão, ou mesmo sair e, elas serão perdidas de novo...
Eu deduzi que poderia ser algo relacionado com linefeed´s "`" da rotina "ALTERAR_A_LISTVIEW", mas eu não creio, pois continuo com o mesmo problema....


Code: Select all

#warn
Gui,1:default

REPOSITORIO_DE_ORDEM := 1 ; INICIAMOS EM 1
setworkingdir,%A_ScriptDir%
F1=%A_ScriptDir%\Registo_Contatos.txt
MainWindowTitle=Registo_Imprimir
Creator=A.Ferreir@
Versão=1.0

dlm:=""
total:=6

FormatTime, Portugal, %a_now% L2070, dddd MMMM yyyy-MM-dd
time:=a_hour . ":" a_min
portugal2:= portugal . "   " . time

transform,T,chr,09                  
gosub,testfile

Gui, Add, StatusBar,,Created by %creator%   %versão%     %portugal%
Gui, Color, +BEBEBE ; Cor do backround 2
Gui, Font, s12 cBlack, Tahoma
header1:="ID:| Designação:| Telefone:| Fax:| E-Mail:| Morada:"

Gui, Add, GroupBox, cBlue x12 y5 w1077 h325, Informações:    
Gui, add, ListView, backgroundblack cCDCD00  r5 x20 y25 h296 w1062 gLVa vLV1 +altsubmit, %header1%
Lv_ModifyCol(1, 50),Lv_ModifyCol(2, 220),Lv_ModifyCol(3, 110),Lv_ModifyCol(4, 110),Lv_ModifyCol(5, 220),Lv_ModifyCol(6, 350)  
   gosub,fill
Gui Add, GroupBox, -cBlue x12 y345 w190 h54, Pesquisar dados: 
Gui, Add, Edit,  x21  y366 w172 h28 gFind vSrc,    
Gui Add, GroupBox, -cBlue x215 y345 w240 h54, Eliminar linha (s): 
Gui, Add, Button, x225  y365 w220 h28 gEliminarx, Eliminar selecionados (as)  
Gui Add, GroupBox, -cBlue x468 y345 w200 h54, Imprimir Lista: 
Gui, Add, Button, x480  y365 w180 h28 gPrint2, Imprimir lista  ; Fazer codigo botao IMPRIMIR-----------
Gui Add, GroupBox, -cBlue x12 y402 w820 h140, Registo: 
Gui Add, GroupBox, -cBlue x845 y402 w145 h140,  
Gui, add, Text,  x30 y428, Designação:                  
Gui, Add, Edit,  x25  y450 w300 h28 vNOME,    
Gui, add, text,  x355  y428, Telefone:                         
Gui, add, Edit,  x350  y450 w120 h28 vFONE,   
Gui, Add, text, x500 y428, Fax:
Gui, Add, Edit, vINFORM_COMPL x495 y450 w120 h28 
Gui, Add, text, x30 y482 w100 h20, E-Mail:      
Gui, Add, Edit, x25  y503 w240 h28 vNPP, 
Gui, add, Text,  x300 y482, Morada:                  
Gui, Add, Edit,  x295  y503 w520 h28 vMorada,    ; Variavel morada-------------------
Gui, Add, Button,x858 y420 w120  h30 gAdd , Guardar      
Gui, Add, Button,x858 y460 w120  h30 gLimpa, Limpar  
Gui, Add, Button,x858 y500 w120  h30 gSair2, Sair  
Gui, show, xCenter yCenter w1100 h580, %MainWindowTitle%   
Menu, CMenu, Add, Eliminar, menuDo
Menu, CMenu, Add, Editar , menuDo
Return
; -------------------------------------------
Guiclose:
Sair2:
ExitApp
;--------------------------------------------

;============ case-1 PRINT_WYS ====================
print2:
Gui,1:submit,nohide
   Header =
   Loop, % LV_GetCount( "Col" )         ; Loop for however many columns are in the listview.
     {
     LV_GetText( myHeader, 0, A_INDEX ) ; Get column header.
     Header .= myHeader . "; "           ; Build output data.
     }

;-- check maximal lenght from each column ---
FilePrint=%A_ScriptDir%\%MainWindowTitle%.txt ; Nome do ficheiro txt "contatos" para impressão
ifexist,%fileprint%
   filedelete,%fileprint%
ControlGet, Listx, List, , SysListView321,%MainWindowTitle%
dlm:=";" 
total:=6  
e5x:=""                                             ;- <<< maybe add a new delimiter which not exists in column
stringreplace,listx,listx,`t,%dlm%,all
e5x .= header . "`r`n"
e5x .= listx 

tx:=""
loop,%total%
  T%a_index%:=0
loop,%total%
  L%a_index%:=0
	Loop,parse,e5x,`n,`r
     {
	 lr=%a_loopfield%
     if lr=
       continue
	 i=0
	 loop,%total%                           ;- get max lenght from x columns
	    {
		i++
        StringSplit,A,lr,%dlm%
        stringlen,L%i%,A%i%
        if (T%i%<L%i%)
           T%i%:=(L%i%+1)                   ;-maximal lenght columnX+1
		}
	 }
;- x columns
loop,%total%	 
 Tx .= "{:" . T%a_index% . "}" . dlm
stringtrimright,tx,tx,1
loop,%total%
  a%a_index%:=""
lr=
e:=""
e .= " " . portugal2 . "                                      A.Ferreir@`r`n--------------------------------------                                      ----------`r`n`n"

Loop, parse,e5x, `n,`r
 {
 lr=%a_loopfield%
 if lr=
    continue
 a :=StrSplit(lr,dlm )
 e .= Format(tx . "`r`n",a*)
 }
fileappend,%e%,%fileprint%
run,%fileprint% 
e=
a=
e5x=
listx=
return
;=============================================


Add:
Gui, submit, nohide                             
Fileappend,%nome%`;%fone%`;%INFORM_COMPL%;%NPP%;%Morada%`r`n,%f1%   ;- LINHA ATUALIZADA COM AS INFORMACOES COMPLEMENTARES.
gosub,fill
sleep,1500
GuiControl,1:,fone,
GuiControl,1:,nome,
GuiControl,1:,INFORM_COMPL,
GuiControl,1:,NPP, 
GuiControl,1:,Morada, 
Return


;-------------- Fill Listview -----------
Fill:
Gui,1:default
gui,1:listview,LV1
LV_Delete()
i=0
loop,read,%F1%
  {
  LR=%A_loopReadLine%
  if LR=
     continue
   i++
loop,%total%
  C%a_index%:=""
      stringsplit,C,LR,`;,
   LV_Add("",I, c1,c2,c3,c4,c5,c6) ; LINHA TUALIZADA COM O C3 (INFORMACOES COMPLEMENTARES).
  }
LV_ModifyCol(1, "Sort Logical")  
LV_Modify(LV_GetCount(), "Vis")
return
;----------- Listview click on row -------------------------------
LVa:
Gui,1:Submit,nohide
if A_GuiEvent = Normal
  {
  LV_GetText(C2,A_EventInfo,2) 	; LINHAS ATUALIZADAS
  LV_GetText(C3,A_EventInfo,3)  ; LINHAS ATUALIZADAS
  LV_GetText(C4,A_EventInfo,4) 	; LINHAS ATUALIZADAS
  LV_GetText(C5,A_EventInfo,5) 	; LINHAS ATUALIZADAS
  LV_GetText(C6,A_EventInfo,6) 	; LINHAS ATUALIZADAS
  cx=%c2%;%c3%;%c4%;%c5%;%c6%; 			; LINHAS ATUALIZADAS
  RN:=LV_GetNext("C")
  RF:=LV_GetNext("F")
  GC:=LV_GetCount()
  }
  
;----------- Listview Opções Rightclick (Eliminar / Alterar) -----
if A_GuiEvent = Rightclick
  {
  LV_GetText(C2,A_EventInfo,2) ; LINHAS ATUALIZADAS
  LV_GetText(C3,A_EventInfo,3) ; LINHAS ATUALIZADAS
  LV_GetText(C4,A_EventInfo,4) ; LINHAS ATUALIZADAS
  LV_GetText(C5,A_EventInfo,5) ; LINHAS ATUALIZADAS
  LV_GetText(C5,A_EventInfo,6) ; LINHAS ATUALIZADAS
  cx=%c2%;%c3%;%c4%;%c5%;%c6%
  RN:=LV_GetNext("C")
  RF:=LV_GetNext("F")
  GC:=LV_GetCount()
  goto,menux 
  }   
;----------- Listview Opções Doubleclick (Alterar) -----------------
if A_GuiEvent = DoubleClick
goto,editarx
return 
;------------- MENU - When Rightclick on row -----------------------
menux:
MouseGetPos, musX, musY
Menu, CMenu, Show, %musX%,%musY%
return
menudo:
If (A_ThisMenuItem = "Eliminar")
   gosub,Eliminarx
If (A_ThisMenuItem = "Editar")
   gosub,Editarx
return
;-------------- Limpar Dados dos Campos ----------------------------------------
Limpa:             ; Limpa os dados do campo
Gui, submit, nohide 
GuiControl,1:,fone,
GuiControl,1:,nome,
GuiControl,1:,INFORM_COMPL,
GuiControl,1:,Src,
GuiControl,1:,NPP,
GuiControl,1:,Morada,
return    
;-------------- Eliminar Dados dos Campos ----------------------------------------
Eliminarx2:
Gui,1:default
gui,1:listview,LV1
   if RF=0
      return
   ;LV_GetText(C1, RF, 1)
   LV_GetText(C2, RF, 2)
   LV_GetText(C3, RF, 2)
   LV_GetText(C4, RF, 2)
   LV_GetText(C5, RF, 2)
   LV_GetText(C6, RF, 2)
   CT=%C2%;%C3%;%C4%;%C5%;%C6%; 			 ; LINHA TUALIZADA COM O C3 (INFORMACOES COMPLEMENTARES).
   msgbox, 262180, APAGAR ,Tem a certeza que deseja eliminar a (s) linha (s) selecionada (s)?
   IfMsgBox,No
      Return
   LV_Delete(RF)
      FileRead,AA,%F1%
      Filedelete,%F1%
      StringReplace,BB,AA,%ct%`r`n,,
      Fileappend,%BB%,%F1%
return	  
;--------------- DELETE multiple selected rows --------------
Eliminarx:
C1 =
RF = 0
RFL =
Loop
   {
   RF:=LV_GetNext(RF)
   if RF=0
      break
   RFL = %RF%|%RFL%
   LV_GetText(C1_Temp, RF, 1)
   C1 = %C1%`n%C1_Temp%
  }
if C1 !=
 {
   msgbox, 262180, APAGAR , Tem a certeza que deseja eliminar a (s) linha (s) selecionada (s)? 
   IfMsgBox,No
      Return
   Else
   {
      Loop, parse, RFL, |
       LV_Delete(A_LoopField)
     filedelete,%F1%
     Loop % LV_GetCount()
        {
        BX1=
        BX2=
        BX3=
        BX4=
        BX5=
        BX6=
        LV_GetText(BX2,A_INDEX,2) ; LINHA ATUALIZADA
		LV_GetText(BX3,A_INDEX,3) ; LINHA ATUALIZADA
		LV_GetText(BX4,A_INDEX,4) ; LINHA ATUALIZADA
        LV_GetText(BX5,A_INDEX,5) ; LINHA ATUALIZADA
        LV_GetText(BX6,A_INDEX,6) ; LINHA ATUALIZADA
        Fileappend,%BX2%`;%BX3%`;%BX4%;%BX5%;%BX6%`r`n,%F1%
       }
   }
      C1=
      C2=
      C3=
      C4=
      C5=
      C6=
 }
return
;----------------------------------------------------------------------------------------------------------------------------------------------- Imprimir
Imprimir: 
; Registo_Contatos.txt
return
;--------------- modifica ----------------
Editarx:
Gui,1:submit, nohide ; Manter janela 1
;Gui,3: +Alwaysontop
Gui,3:Color, +8B8B00; Cor do backround Alterar
Gui,3:Font, s12 cBlack, Tahoma
Gui,3:Add, GroupBox, -cWhite x12 y8 w500 h54, Designação: 
Gui,3:Add,Edit, x20 y28 w485 h28 vA32, %C2%
Gui,3:Add, GroupBox, -cWhite x12 y65 w148 h54, Telefone:
Gui,3:Add,Edit , x22 y85 w130 h28 vA31, %C3%
Gui,3:Add, GroupBox, -cWhite x175 y65 w148 h54, Fax:
Gui,3:Add, Edit, x185 y85 w130 h28 vVARIAVEL_DAS_INFORMACOES_COMPLEMENTARES, %C4%
Gui,3:Add, GroupBox, -cWhite x12 y120 w312 h54, E-Mail:      
Gui,3:Add, Edit, x22 y140 w295 h28 vC5, %C5% 
Gui,3:Add, GroupBox, -cWhite x12 y175 w500 h56, Morada: 
Gui,3:Add,Edit , x20 y195 w485 h28 vC6, %C6%
Gui,3:Add, Button, x160 y250 w90 h28 gCancelar, &Cancelar
Gui,3:Add, Button, x260 y250 w90 h28 gALTERAR_A_LISTVIEW, Alterar
Gui,3:Show, xCenter yCenter w520 h320, ALTERAR:
Gui,3:Font, s8 cBlack, Tahoma
Gui,3:Add, StatusBar, , Created by %creator%   %versão%
GuiControl,3:Focus,A31
send,^{end}
return
;-------------
ALTERAR_A_LISTVIEW:
Gui,3: Submit, nohide
Gui,1: Default
Lv_Modify(RN, "Col2", A32)
Lv_Modify(RN, "Col3", A31)
Lv_Modify(RN, "Col4", VARIAVEL_DAS_INFORMACOES_COMPLEMENTARES)
Lv_Modify(RN, "Col5", C5)
Lv_Modify(RN, "Col6", C6)

FileRead, CONTEUDO_ATUAL_DO_ARQUIVO, %A_ScriptDir%\Registo_Contatos.txt
StringReplace, NOVO_CONTEUDO_DO_ARQUIVO, CONTEUDO_ATUAL_DO_ARQUIVO, %C2%`;%C3%`;%C4%`;%C5%`;%C6%,                                                %A32%`;%A31%`;%VARIAVEL_DAS_INFORMACOES_COMPLEMENTARES%`;%C5%`;%C6%
FileAppend, %NOVO_CONTEUDO_DO_ARQUIVO%, %A_ScriptDir%\Registo_NOVO.txt
FileRead, ARQUIVO_ESCRITO, %A_ScriptDir%\Registo_NOVO.txt
If (ARQUIVO_ESCRITO = NOVO_CONTEUDO_DO_ARQUIVO)
{
FileMove, %A_ScriptDir%\Registo_NOVO.txt, %A_ScriptDir%\Registo_Contatos.txt, 1
FileRead, CONTEUDO_ATUAL_DO_ARQUIVO, %f1%
If (ErrorLevel)
{
msgbox, 0x10, ERRO: , Houve um erro na gravação dos dados na alteração do arquivo. Por favor, tente novamente.
Return
}
else
{
msgbox, 0, SUCESSO: , Alteração efetuada com sucesso !
Gui, 3: Destroy
Return
}
}
Else
{
msgbox, 0x10, ERRO: , Houve um erro na gravação dos dados na alteração do arquivo. Por favor, tente novamente.
}
Return
;--------------------------------------------------------------------------
Cancelar:
Gui,3: destroy
return
;-------------------------------------------------------------------------------------------
3GuiClose:
3GuiEscape:
Gui, 3:Destroy
return
3ButtonOK:
Gui,3:submit
if A31=
   {
   Gui,3: Destroy
   return
   }
FileRead, FileContent, %f1%
FileDelete, %f1%
StringReplace, FileContent, FileContent, %C1%`;%C2%, %A31%`;%A32%`;%C5%`;%C6%`;
FileAppend, %FileContent%, %f1%
GoSub,fill
Gui,3:destroy
return
;------------------- SEARCH -------------------------------
Find:
Gui,1: Submit, Nohide
Gui,1:listview, LV1
checkempty:
if (src="")
   {
   settimer,checkempty,off
   goto,fill
   return
   }
settimer,checkempty,1000
LV_Delete()
  loop,read,%f1%
  {
  LR=%A_loopReadLine%
  if SRC<>
     {
     if LR contains %src%
       {
       stringsplit,C,A_LoopReadLine,`;
       LV_Add("",A_INDEX, C1,C2,C3,C4,C5,C6) ; LINHA TUALIZADAS
       }
     }
  else
   continue
   }
LV_Modify(LV_GetCount(), "Vis")
if (SRC="")
  goto,Fill
return
;--------------- create testfile ----------------------
testfile:
ifnotexist,%f1%
{
  e1=
  (Ltrim Join`r`n

  )
FileAppend,%e1%`r`n,%f1%
e1=
}
Return
User avatar
Gio
Posts: 1247
Joined: 30 Sep 2013, 10:54
Location: Brazil

Re: Correção de BUGs na Lista Telefónica  Topic is solved

12 Apr 2019, 10:17

Bom dia AFerreira.

Havia erros em várias linhas:
1. Na rotina LVa, uma das condicionais (a do rightclick) estava escrevendo o conteúdo do campo 5 da listview em C5 e logo depois o conteúdo do campo 6 também em C5.
2. A variável ligada aos campos email e morada na rotina Editarx era C5 e C6, as mesmas que estavam sendo usadas para colocar os dados nas colunas 5 e 6 da listview. Foram colocadas variáveis diferentes para esses campos.

Code: Select all

#warn
Gui,1:default

REPOSITORIO_DE_ORDEM := 1 ; INICIAMOS EM 1
setworkingdir,%A_ScriptDir%
F1=%A_ScriptDir%\Registo_Contatos.txt
MainWindowTitle=Registo_Imprimir
Creator=A.Ferreir@
Versão=1.0

dlm:=""
total:=6

FormatTime, Portugal, %a_now% L2070, dddd MMMM yyyy-MM-dd
time:=a_hour . ":" a_min
portugal2:= portugal . "   " . time

transform,T,chr,09                  
gosub,testfile

Gui, Add, StatusBar,,Created by %creator%   %versão%     %portugal%
Gui, Color, +BEBEBE ; Cor do backround 2
Gui, Font, s12 cBlack, Tahoma
header1:="ID:| Designação:| Telefone:| Fax:| E-Mail:| Morada:"

Gui, Add, GroupBox, cBlue x12 y5 w1077 h325, Informações:    
Gui, add, ListView, backgroundblack cCDCD00  r5 x20 y25 h296 w1062 gLVa vLV1 +altsubmit, %header1%
Lv_ModifyCol(1, 50),Lv_ModifyCol(2, 220),Lv_ModifyCol(3, 110),Lv_ModifyCol(4, 110),Lv_ModifyCol(5, 220),Lv_ModifyCol(6, 350)  
   gosub,fill
Gui Add, GroupBox, -cBlue x12 y345 w190 h54, Pesquisar dados: 
Gui, Add, Edit,  x21  y366 w172 h28 gFind vSrc,    
Gui Add, GroupBox, -cBlue x215 y345 w240 h54, Eliminar linha (s): 
Gui, Add, Button, x225  y365 w220 h28 gEliminarx, Eliminar selecionados (as)  
Gui Add, GroupBox, -cBlue x468 y345 w200 h54, Imprimir Lista: 
Gui, Add, Button, x480  y365 w180 h28 gPrint2, Imprimir lista  ; Fazer codigo botao IMPRIMIR-----------
Gui Add, GroupBox, -cBlue x12 y402 w820 h140, Registo: 
Gui Add, GroupBox, -cBlue x845 y402 w145 h140,  
Gui, add, Text,  x30 y428, Designação:                  
Gui, Add, Edit,  x25  y450 w300 h28 vNOME,    
Gui, add, text,  x355  y428, Telefone:                         
Gui, add, Edit,  x350  y450 w120 h28 vFONE,   
Gui, Add, text, x500 y428, Fax:
Gui, Add, Edit, vINFORM_COMPL x495 y450 w120 h28 
Gui, Add, text, x30 y482 w100 h20, E-Mail:      
Gui, Add, Edit, x25  y503 w240 h28 vNPP, 
Gui, add, Text,  x300 y482, Morada:                  
Gui, Add, Edit,  x295  y503 w520 h28 vMorada,    ; Variavel morada-------------------
Gui, Add, Button,x858 y420 w120  h30 gAdd , Guardar      
Gui, Add, Button,x858 y460 w120  h30 gLimpa, Limpar  
Gui, Add, Button,x858 y500 w120  h30 gSair2, Sair  
Gui, show, xCenter yCenter w1100 h580, %MainWindowTitle%   
Menu, CMenu, Add, Eliminar, menuDo
Menu, CMenu, Add, Editar , menuDo
Return
; -------------------------------------------
Guiclose:
Sair2:
ExitApp
;--------------------------------------------

;============ case-1 PRINT_WYS ====================
print2:
Gui,1:submit,nohide
   Header =
   Loop, % LV_GetCount( "Col" )         ; Loop for however many columns are in the listview.
     {
     LV_GetText( myHeader, 0, A_INDEX ) ; Get column header.
     Header .= myHeader . "; "           ; Build output data.
     }

;-- check maximal lenght from each column ---
FilePrint=%A_ScriptDir%\%MainWindowTitle%.txt ; Nome do ficheiro txt "contatos" para impressão
ifexist,%fileprint%
   filedelete,%fileprint%
ControlGet, Listx, List, , SysListView321,%MainWindowTitle%
dlm:=";" 
total:=6  
e5x:=""                                             ;- <<< maybe add a new delimiter which not exists in column
stringreplace,listx,listx,`t,%dlm%,all
e5x .= header . "`r`n"
e5x .= listx 

tx:=""
loop,%total%
  T%a_index%:=0
loop,%total%
  L%a_index%:=0
	Loop,parse,e5x,`n,`r
     {
	 lr=%a_loopfield%
     if lr=
       continue
	 i=0
	 loop,%total%                           ;- get max lenght from x columns
	    {
		i++
        StringSplit,A,lr,%dlm%
        stringlen,L%i%,A%i%
        if (T%i%<L%i%)
           T%i%:=(L%i%+1)                   ;-maximal lenght columnX+1
		}
	 }
;- x columns
loop,%total%	 
 Tx .= "{:" . T%a_index% . "}" . dlm
stringtrimright,tx,tx,1
loop,%total%
  a%a_index%:=""
lr=
e:=""
e .= " " . portugal2 . "                                      A.Ferreir@`r`n--------------------------------------                                      ----------`r`n`n"

Loop, parse,e5x, `n,`r
 {
 lr=%a_loopfield%
 if lr=
    continue
 a :=StrSplit(lr,dlm )
 e .= Format(tx . "`r`n",a*)
 }
fileappend,%e%,%fileprint%
run,%fileprint% 
e=
a=
e5x=
listx=
return
;=============================================


Add:
Gui, submit, nohide                             
Fileappend,%nome%`;%fone%`;%INFORM_COMPL%;%NPP%;%Morada%`r`n,%f1%   ;- LINHA ATUALIZADA COM AS INFORMACOES COMPLEMENTARES.
gosub,fill
sleep,1500
GuiControl,1:,fone,
GuiControl,1:,nome,
GuiControl,1:,INFORM_COMPL,
GuiControl,1:,NPP, 
GuiControl,1:,Morada, 
Return


;-------------- Fill Listview -----------
Fill:
Gui,1:default
gui,1:listview,LV1
LV_Delete()
i=0
loop,read,%F1%
  {
  LR=%A_loopReadLine%
  if LR=
     continue
   i++
loop,%total%
  C%a_index%:=""
      stringsplit,C,LR,`;,
   LV_Add("",I, c1,c2,c3,c4,c5,c6) ; LINHA TUALIZADA COM O C3 (INFORMACOES COMPLEMENTARES).
  }
LV_ModifyCol(1, "Sort Logical")  
LV_Modify(LV_GetCount(), "Vis")
return
;----------- Listview click on row -------------------------------
LVa:
Gui,1:Submit,nohide
if A_GuiEvent = Normal
  {
  LV_GetText(C2,A_EventInfo,2) 	; LINHAS ATUALIZADAS
  LV_GetText(C3,A_EventInfo,3)  ; LINHAS ATUALIZADAS
  LV_GetText(C4,A_EventInfo,4) 	; LINHAS ATUALIZADAS
  LV_GetText(C5,A_EventInfo,5) 	; LINHAS ATUALIZADAS
  LV_GetText(C6,A_EventInfo,6) 	; LINHAS ATUALIZADAS
  cx=%c2%;%c3%;%c4%;%c5%;%c6%; 			; LINHAS ATUALIZADAS
  RN:=LV_GetNext("C")
  RF:=LV_GetNext("F")
  GC:=LV_GetCount()
  }
  
;----------- Listview Opções Rightclick (Eliminar / Alterar) -----
if A_GuiEvent = Rightclick
  {
  LV_GetText(C2,A_EventInfo,2) ; LINHAS ATUALIZADAS
  LV_GetText(C3,A_EventInfo,3) ; LINHAS ATUALIZADAS
  LV_GetText(C4,A_EventInfo,4) ; LINHAS ATUALIZADAS
  LV_GetText(C5,A_EventInfo,5) ; LINHAS ATUALIZADAS
  LV_GetText(C6,A_EventInfo,6) ; LINHAS ATUALIZADAS
  cx=%c2%;%c3%;%c4%;%c5%;%c6%
  RN:=LV_GetNext("C")
  RF:=LV_GetNext("F")
  GC:=LV_GetCount()
  goto,menux 
  }   
;----------- Listview Opções Doubleclick (Alterar) -----------------
if A_GuiEvent = DoubleClick
goto,editarx
return 
;------------- MENU - When Rightclick on row -----------------------
menux:
MouseGetPos, musX, musY
Menu, CMenu, Show, %musX%,%musY%
return
menudo:
If (A_ThisMenuItem = "Eliminar")
   gosub,Eliminarx
If (A_ThisMenuItem = "Editar")
   gosub,Editarx
return
;-------------- Limpar Dados dos Campos ----------------------------------------
Limpa:             ; Limpa os dados do campo
Gui, submit, nohide 
GuiControl,1:,fone,
GuiControl,1:,nome,
GuiControl,1:,INFORM_COMPL,
GuiControl,1:,Src,
GuiControl,1:,NPP,
GuiControl,1:,Morada,
return    
;-------------- Eliminar Dados dos Campos ----------------------------------------
Eliminarx2:
Gui,1:default
gui,1:listview,LV1
   if RF=0
      return
   ;LV_GetText(C1, RF, 1)
   LV_GetText(C2, RF, 2)
   LV_GetText(C3, RF, 2)
   LV_GetText(C4, RF, 2)
   LV_GetText(C5, RF, 2)
   LV_GetText(C6, RF, 2)
   CT=%C2%;%C3%;%C4%;%C5%;%C6%; 			 ; LINHA TUALIZADA COM O C3 (INFORMACOES COMPLEMENTARES).
   msgbox, 262180, APAGAR ,Tem a certeza que deseja eliminar a (s) linha (s) selecionada (s)?
   IfMsgBox,No
      Return
   LV_Delete(RF)
      FileRead,AA,%F1%
      Filedelete,%F1%
      StringReplace,BB,AA,%ct%`r`n,,
      Fileappend,%BB%,%F1%
return	  
;--------------- DELETE multiple selected rows --------------
Eliminarx:
C1 =
RF = 0
RFL =
Loop
   {
   RF:=LV_GetNext(RF)
   if RF=0
      break
   RFL = %RF%|%RFL%
   LV_GetText(C1_Temp, RF, 1)
   C1 = %C1%`n%C1_Temp%
  }
if C1 !=
 {
   msgbox, 262180, APAGAR , Tem a certeza que deseja eliminar a (s) linha (s) selecionada (s)? 
   IfMsgBox,No
      Return
   Else
   {
      Loop, parse, RFL, |
       LV_Delete(A_LoopField)
     filedelete,%F1%
     Loop % LV_GetCount()
        {
        BX1=
        BX2=
        BX3=
        BX4=
        BX5=
        BX6=
        LV_GetText(BX2,A_INDEX,2) ; LINHA ATUALIZADA
		LV_GetText(BX3,A_INDEX,3) ; LINHA ATUALIZADA
		LV_GetText(BX4,A_INDEX,4) ; LINHA ATUALIZADA
        LV_GetText(BX5,A_INDEX,5) ; LINHA ATUALIZADA
        LV_GetText(BX6,A_INDEX,6) ; LINHA ATUALIZADA
        Fileappend,%BX2%`;%BX3%`;%BX4%;%BX5%;%BX6%`r`n,%F1%
       }
   }
      C1=
      C2=
      C3=
      C4=
      C5=
      C6=
 }
return
;----------------------------------------------------------------------------------------------------------------------------------------------- Imprimir
Imprimir: 
; Registo_Contatos.txt
return
;--------------- modifica ----------------
Editarx:
Gui,1:submit, nohide ; Manter janela 1
;Gui,3: +Alwaysontop
Gui,3:Color, +8B8B00; Cor do backround Alterar
Gui,3:Font, s12 cBlack, Tahoma
Gui,3:Add, GroupBox, -cWhite x12 y8 w500 h54, Designação: 
Gui,3:Add,Edit, x20 y28 w485 h28 vA32, %C2%
Gui,3:Add, GroupBox, -cWhite x12 y65 w148 h54, Telefone:
Gui,3:Add,Edit , x22 y85 w130 h28 vA31, %C3%
Gui,3:Add, GroupBox, -cWhite x175 y65 w148 h54, Fax:
Gui,3:Add, Edit, x185 y85 w130 h28 vVARIAVEL_DAS_INFORMACOES_COMPLEMENTARES, %C4%
Gui,3:Add, GroupBox, -cWhite x12 y120 w312 h54, E-Mail:      
Gui,3:Add, Edit, x22 y140 w295 h28 vNOVO_EMAIL, %C5% 
Gui,3:Add, GroupBox, -cWhite x12 y175 w500 h56, Morada: 
Gui,3:Add,Edit , x20 y195 w485 h28 vNOVA_MORADA, %C6%
Gui,3:Add, Button, x160 y250 w90 h28 gCancelar, &Cancelar
Gui,3:Add, Button, x260 y250 w90 h28 gALTERAR_A_LISTVIEW, Alterar
Gui,3:Show, xCenter yCenter w520 h320, ALTERAR:
Gui,3:Font, s8 cBlack, Tahoma
Gui,3:Add, StatusBar, , Created by %creator%   %versão%
GuiControl,3:Focus,A31
send,^{end}
return
;-------------
ALTERAR_A_LISTVIEW:
Gui,3: Submit, nohide
Gui,1: Default
Lv_Modify(RN, "Col2", A32)
Lv_Modify(RN, "Col3", A31)
Lv_Modify(RN, "Col4", VARIAVEL_DAS_INFORMACOES_COMPLEMENTARES)
Lv_Modify(RN, "Col5", NOVO_EMAIL)
Lv_Modify(RN, "Col6", NOVA_MORADA)

FileRead, CONTEUDO_ATUAL_DO_ARQUIVO, %A_ScriptDir%\Registo_Contatos.txt
StringReplace, NOVO_CONTEUDO_DO_ARQUIVO, CONTEUDO_ATUAL_DO_ARQUIVO, %C2%`;%C3%`;%C4%`;%C5%`;%C6%,                                                %A32%`;%A31%`;%VARIAVEL_DAS_INFORMACOES_COMPLEMENTARES%`;%NOVO_EMAIL%`;%NOVA_MORADA%
FileAppend, %NOVO_CONTEUDO_DO_ARQUIVO%, %A_ScriptDir%\Registo_NOVO.txt
FileRead, ARQUIVO_ESCRITO, %A_ScriptDir%\Registo_NOVO.txt
If (ARQUIVO_ESCRITO = NOVO_CONTEUDO_DO_ARQUIVO)
{
FileMove, %A_ScriptDir%\Registo_NOVO.txt, %A_ScriptDir%\Registo_Contatos.txt, 1
FileRead, CONTEUDO_ATUAL_DO_ARQUIVO, %f1%
If (ErrorLevel)
{
msgbox, 0x10, ERRO: , Houve um erro na gravação dos dados na alteração do arquivo. Por favor, tente novamente.
Return
}
else
{
msgbox, 0, SUCESSO: , Alteração efetuada com sucesso !
Gui, 3: Destroy
Return
}
}
Else
{
msgbox, 0x10, ERRO: , Houve um erro na gravação dos dados na alteração do arquivo. Por favor, tente novamente.
}
Return
;--------------------------------------------------------------------------
Cancelar:
Gui,3: destroy
return
;-------------------------------------------------------------------------------------------
3GuiClose:
3GuiEscape:
Gui, 3:Destroy
return
3ButtonOK:
Gui,3:submit
if A31=
   {
   Gui,3: Destroy
   return
   }
FileRead, FileContent, %f1%
FileDelete, %f1%
StringReplace, FileContent, FileContent, %C1%`;%C2%, %A31%`;%A32%`;%C5%`;%C6%`;
FileAppend, %FileContent%, %f1%
GoSub,fill
Gui,3:destroy
return
;------------------- SEARCH -------------------------------
Find:
Gui,1: Submit, Nohide
Gui,1:listview, LV1
checkempty:
if (src="")
   {
   settimer,checkempty,off
   goto,fill
   return
   }
settimer,checkempty,1000
LV_Delete()
  loop,read,%f1%
  {
  LR=%A_loopReadLine%
  if SRC<>
     {
     if LR contains %src%
       {
       stringsplit,C,A_LoopReadLine,`;
       LV_Add("",A_INDEX, C1,C2,C3,C4,C5,C6) ; LINHA TUALIZADAS
       }
     }
  else
   continue
   }
LV_Modify(LV_GetCount(), "Vis")
if (SRC="")
  goto,Fill
return
;--------------- create testfile ----------------------
testfile:
ifnotexist,%f1%
{
  e1=
  (Ltrim Join`r`n

  )
FileAppend,%e1%`r`n,%f1%
e1=
}
Return
É preciso tomar bastante cuidado com o uso das variáveis. Sugiro que nomeie as suas variáveis com nomes mais descritivos, a variável C5, por exemplo, deveria ser algo como CAMPO_EMAIL_DA_LISTVIEW ou então se quiser algo mais curto pelo menos LISTVIEW_EMAIL. Isso diminui bastante a chance de erros e melhora a leitura do seu código, pois é difícil manter na cabeça o que exatamente está no campo 5.
AFerreira
Posts: 14
Joined: 01 Mar 2017, 07:07

Re: Correção de BUGs na Lista Telefónica

12 Apr 2019, 10:58

´
:facepalm:
Perfeito!
Obrigado Gio..!!!

:beer: :beer: :beer:
garry
Posts: 3758
Joined: 22 Dec 2013, 12:50

Re: Correção de BUGs na Lista Telefónica

16 Apr 2019, 02:21

@Gio , obrigado pela ajuda
@AFerreira, é uma boa interface gráfica ( GUI )

Return to “Ajuda e Suporte Geral”

Who is online

Users browsing this forum: No registered users and 16 guests