Pagine: 1 ... 11 12 [13] 14
Introduzione
Buongiorno, oggi vi insegnerò come utilizzare al meglio tutte le unità esterne, tra le quali mouse, stampante, scanner...
Inizio a dirvi subito che gli esempi e i termini che si utilizzeranno durante la guida saranno fedeli al free-pascal.

Ecco le librerie:

Keyboard Tastiera (funzioni avanzate)/Joystick (qualsiasi tipo)
Mouse Mouse/Tavola grafica      
Printer Stampante/Plotter
//      Unità memoria esterne (PenDrive,Disco,Floppy ecc.)

Cercando con Google si possono trovare link per lo scaricamento di queste appartenenti alla rtl (run time library)

Keyboard
Ovviamente, appiamo bene che per input pascal, si utilizza read(X:String)/readln(X:String), ma per delle funzioni avanzate della tastiera, usare la libreria Keyboard é fondamentale. Molti di voi sicuramente saranno perplessi e si chiederanno cosa si potrebbe fare con queste funzioni AVANZATE, ed é per questo che descriverò subito la loro utilità:

  • Utilizzare tasti particolari (come F12 o pag. su o up (freccietta) senza l'utilizzo delle direttive
  • Utilizzare un qualsiasi tipo di joystick


Per inizializzare il driver della tastiera o joystick utilizzare la procedura InitKeyboard, per disattivarlo DoneKeyboard, entrambe senza parametri.

La maggior parte delle costanti della libreria son tasti particolari:

KbdF1        F1
KbdF2        F2
KbdF3        F3
KbdF4        F4
ecc.
KbdAlt        Alt
KbdCtrl      Crtl  
KbdApps   Menù principale
KbdDown Freccetta Giù      
KbdUp       Freccietta Sù        
KbdRight  Freccetta Destra      
KbdLeft     Freccetta Sinistra  
KbdPgDN Pagina Giù        
KbdPgUP  Pagina Su
KbdHome Home
KbdShift    Shift            

KbdDelete          Nascondi carattere                          KbdInsert           Fai apparire carattere

Per maggiori dettagli: http://www.freepascal.org/docs-html/rtl/keyboard/index.html

Mouse
Come dice la libreria stessa, mouse serve per utilizzare in modo perfetto il mouse. Inizio subito con un esempio di codice:
Codice: [Seleziona]

Program EsmpioMouse;
Uses Graph,Mouse;
Var X,Y:integer;

Begin
Gd:=detect;
InitGraph(Gd,Gm,’C//:FPC’);
RestetMouse;
SetMouseWindow(0,0,1000,1000);
{Ecco un bottone}
Rectangle(0,0,100,100);
{Diamogli il valore di bottone per il mouse}
X:=GetmouseX;
Y:=GetmouseY;
If ((X>0) and (Y>0) and (X<100) and (Y<100) then
Write(Fine programma);
Readln;
Resetmouse;
End.


Ecco le funzioni:
Resetmouse  Restetta il mouse, lo inizializza o lo chiude, da usare all’inizio e alla fine per il corretto funzionamento della prossima funzione.
Setmousewindows  In collaborazione con resetmouse da le coordinate di un rettangolo limite delle operazioni col mouse.
GetmouseX/Y Mi sembra abbastanza ovvio guardando il codice: Restituisce la posizione del mouse rispetto all’asse X o Y.

Il programma è molto incompleto anche se funzionante, mancano:
Left/Rightpressed Restituisce true se premuto il tasto sinistro o destro (left/right) del mouse.
Mouseinstalled: Restituisce true se installato un mouse.

Per concludere, la tavola grafica è molto semplice da usare, basta registrare in memoria la posizione del click del mouse e subito dopo rispondere cambiando il colore di quel pixel o di quei pixel. Infatti la maggior parte delle tavole grafiche sono corrispondenti ai driver dei mouse.

Per maggiori dettagli:

Siamo giunti finalmente alla libreria più attesa, printer che permette di stampare da stampante (o plotter) testi in/output.
Ecco come fare, in maniera molto semplice:

Initprinter: Inizializza driver stampante o plotter;
Assinglst: stampa testo (parametro);
IsLstAvaiable: controlla se c’è un driver stampante o plotter installato;

Nulla di più semplice, ma per dettagli: http:// http://www.freepascal.org/docs-html/rtl/printer/index-5.html

Altro
Una volta inserita un’unità esterna, essa sarà parte di quella interna quindi per aprire unità esterne, basta inserirle nel computer e aprirle con una directory normale.
Parlando in termini di windows, però, c’è un cambiamento: Il prefisso “C:” cambia e diventa

E: Per le SD card
D: Per i compact disk (DVD RW)
Z: Per le memory card
F: Per le pendrive

Sempre con windows, si può determinare un prefisso di unità esterna, aprendo “computer” o “risorse del computer” (a seconda delle versioni) e vedendo il nome dell’unità appena inserita seguito dal prefisso tra parentesi.
Per altri sistemi operativi, ci sono altri modi sempre semplici.


Vi auguro un buon uso di queste funzioni nei vostri futuri programmi.
Share on Twitter! Digg this story! Del.icio.us Share on Facebook! Technorati Reddit StumbleUpon

Capita spesso che si debba lavorare con le directory e i loro contenuti. Lazarus/Free Pascal permette queste operazioni in maniera facile ed intuitiva.

Segue un piccolo esempio di una Form con un Button (Nome=Button1) e una ListBox(Nome=ListBox1), quando si preme sul button1 il programma legge tutto il contenuto delle cartella in cui si trova l'eseguibile rinomina tutti i file (di 21 caratteri, estensioni comprese) in esso contenuti togliendo i primi 4 caratteri partendo da sinista.

Segue l'esempio, spero possa essere utile a qualcuno.

unit Unit1;


{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;

type

  { TForm1 }

  TForm1 = class(TForm)
    Button1: TButton;
    ListBox1: TListBox;
    procedure Button1Click(Sender: TObject);
  private
    { private declarations }
  public
    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }

procedure TForm1.Button1Click(Sender: TObject);
var
   Info : TSearchRec;
   Count : Longint;
   fecha, fecha2:Tdate;
   fechatmp, fechatmp2:longint;
   Spazio: int64;
   filename:string;
   PercIncrem: double;
   Percorso, NuovoNome: string;
   k: integer;
begin
           Percorso:=Application.Location;
           //se volessi leggere un altra cartella dovrei scrivere: If FindFirst (NomeAltraDirectory + '*',faAnyFile and faDirectory,Info)=0 then
           If FindFirst ('*',faAnyFile and faDirectory,Info)=0 then
           begin
                Repeat
                      With Info do
                      begin
                           if ((Name='.') OR (Name='..')) then
                           begin

                           end
                           else
                           begin
                                If (Attr and faDirectory) = faDirectory then
                                begin
                                     //è una dir e la ignoro
                                end
                                else

                                begin

                                        Spazio:=size; //salvo la dimensione del file (non la uso ma è per far vedere che c'è la possibilità)

                                     filename:=Percorso + Name;

                                     if Length(name)=21 then
                                     begin
                                          NuovoNome:=RightStr(Name,Length(Name)-4);

                                          ListBox1.Items.Add(filename + ' --> ' + NuovoNome);
                                          RenameFile(filename, NuovoNome);
                                     end;

                                end;
                           end;
                      end;
                Until FindNext(info)<>0;
           end;
           FindClose(Info);
           ShowMessage('Terminato');
end;

end.


Share on Twitter! Digg this story! Del.icio.us Share on Facebook! Technorati Reddit StumbleUpon

Quante volte è capitato di dirsi, però ora che ho fatto il programma se lo rendessi multilingua potrei distribuirlo in numero maggiore! Bene questo tutorial spiega i passi per rendere il vostro software multilingua in maniera semplice e multipiattaforma. Tutto questo con l'ausilio dei file INi.


Bene per prima cosa necessitiamo di un file ini che chiameremo lingue.ini (nella stessa cartella dell'eseguibile), così strutturato.


[Lingue]

    ; in questa zona dichiaro le lingue che andrò ad implementare nel mio programma
    Numero=2
    Lingua1=italiano
    Lingua2=inglese

[italiano]
    ;notare che italiano è tutto minuscolo per essere uguale alla lingua dichiarata sopra nella sezione Lingue
    ;per non creare problematiche di alcun tipo in sistemi operativi case-sensitive
    Lbl_Nome=Nome
    Lbl_Cognome=Cognome

[inglese]
    Lbl_Nome=Name
    Lbl_Cognome=Surname


Come seconda cosa andiamo ad analizzare un po di codice Free Pascal per interagire con tale file INI. Creiamo un nuovo progetto con una form che si chiama Form1 e aggiungete tre componenti, una TComboBox e due TLabel. Ecco come sarà il sorgente


unit Unit1;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls
  ,INIFiles {libreria per usare i file ini}
  ;

type

  { TForm1 }

  TForm1 = class(TForm)
    Cmb_Lingue: TComboBox;
    Lbl_Nome: TLabel;
    Lbl_Cognome: TLabel;
    procedure Cmb_LingueChange(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { private declarations }
    procedure CambiaLingua();
  public
    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.lfm}

{ TForm1 }


{ In fase di caricamento delle form inserisco nella combobox le possibili lingue inserite nel file ini}
procedure TForm1.FormCreate(Sender: TObject);
Var
 INI:TINIFile;
 Numero, i: integer;
begin
  INI := TINIFile.Create(Application.Location + 'lingue.ini');
  Numero := StrToInt(INI.ReadString('Lingue','Numero',''));
  for i:=1 to Numero do
  begin
      Cmb_Lingue.Items.Add(INI.ReadString('Lingue','Lingua' + IntToStr(i),''));
  end;
  Ini.Free;
  Cmb_Lingue.Text:=Cmb_Lingue.Items.Strings[0];
  CambiaLingua();
end;


{ Al cambiamento del contenuto della ComboBox cambio i valori delle label }
procedure TForm1.Cmb_LingueChange(Sender: TObject);
begin
     CambiaLingua();
end;

procedure TForm1.CambiaLingua();
var
   i: integer;
   INI:TINIFile;
   Lingua: string;
begin
     Lingua:=Cmb_Lingue.Text;
     INI := TINIFile.Create(Application.Location + 'lingue.ini');
     for i:=0 to Form1.ComponentCount-1 do
     begin
           Form1.Controls[i].Caption:=INI.ReadString(Lingua,Form1.Components[i].Name,'');
     end;
     Ini.Free;
     Cmb_Lingue.Text:=Lingua;
end;

end.

Il codice è abbastanza semplice, è facile dedurne il funzionamento compilandolo. Se avete soluzioni migliori o alternative (ma sempre il più possibile multipiattaforma) mandatemeli tramite messaggio, io provvederò a pubblicarli.

Esempio: www.lazaruspascal.it/esempi/Multilingua.zip

Share on Twitter! Digg this story! Del.icio.us Share on Facebook! Technorati Reddit StumbleUpon

21 Ott 2011 - Codice di attivazione

Cosa succede quando avete finito un software e volete distribuirlo, previa vostra autorizzazione? Questo How To vi viene incontro e vi spiega come io ho affrontato il problema.

La soluzione a tale problema è composta di due parti, un codice php posizionato nel sito dal quale distribuisco il software e dal quale faccio fare l'attivazione del prodotto.


Quella che segue è la classe PHP che mi genera il mio codice di attivazione nel formato: XXXX-XXXX-XXXX-XXXX


[code]

/*

    Classe realizzata da Sammarco Francesco
    Es:

    $OggettoSN = new Serial_Number;
    $CodSer = $OggettoSN->PKV_MakeKey($IdCod);
*/

class Serial_Number
{

    // Costruttore
    function __construct()
    {
    }

    // Distruttore
      public function __destruct()
    {
            //non faccio niente
    }
    private function Shr($a, $b)
    {
        return ($a/(2^$b));
    }


    private function PKV_GetKeyByte($Seed,$a,$b,$c)
    {
        $a = $a % 25;
        $b = $b % 3;
        if( $a % 2 == 0 )
        {
          $result = ( $Seed >> $a ) ^ ( ( $Seed >> $b ) | $c );
        } else
        {
          $result = ( $Seed >> $a ) ^ ( ( $Seed >> $b ) & $c );
        }
        return $result & 0x000000FF;
       }

       private function IntToHex($Variabile,$Num)
       {
           $result=dechex($Variabile);
           $k=$Num-strlen($result);
           for($i=0;$i<$k;$i++)
           {
               $result="0" . $result;
           }
           return strtoupper($result);
       }

    public function PKV_MakeKey($Seed)
    {
          $KeyBytes[0]=$this->PKV_GetKeyByte($Seed, 24, 3, 200);
          $KeyBytes[1]=$this->PKV_GetKeyByte($Seed, 10, 0, 56);
          $KeyBytes[2]=$this->PKV_GetKeyByte($Seed, 1, 2, 91);
          $KeyBytes[3]=$this->PKV_GetKeyByte($Seed, 7, 1, 100);

          $result=$this->IntToHex($Seed,8);
          for ($i=0;$i<=3;$i++)
          {
              $result=$result . $this->IntToHex($KeyBytes[$i],2);
          }
          $valorecs=$this->PKV_GetChecksum($result);
          $result=$result . $valorecs;
          $app="";
          $j=1;
          for ($i=0;$i<strlen($result);$i++)

          {
              if (($j == 4)&&($i<(strlen($result)-1)))
              {
                  $app=$app . $result[$i] . "-";
                  $j=1;
              }else
              {
                  $app=$app . $result[$i];
                  $j++;
              }
          }
          return $app;
    }

    private function PKV_GetChecksum($s)
    {
          $left = 0x0056;
          $right = 0x00AF;
        if(strlen($s) > 0 )
        {
            for( $i = 0 ; $i < strlen( $s ) ; $i++ )
            {
                  $right = $right + Ord($s[$i]);
                  if($right > 0x00FF )
                  {
                    $right=$right-0x00FF;
                }
                  $left=$left+$right;
                  if($left > 0x00FF )
                  {
                    $left=$left-0x00FF;
                }
            }
        }
          $sum = ( $left << 8 ) + $right;
          $result = $this->IntToHex($sum, 4 );
        return $result;
    }

}

?>

[/code]




Usare tale classe è molto molto semplice basta usare il codice (sempre in php):

    $OggettoSN = new Serial_Number;
    $CodSer = $OggettoSN->PKV_MakeKey($IdCod);   

Dove $IdCod equivale all'inizializzatore da cui mi ricavo il mio codice di attivazione e $CodSer è il nostro tanto agognato codice di serie.

Per rendere la nostra classe unica e diversa da questo codice di esempio basta cambiare i parametri numerici nella funzione PKV_GetKeyByte

         $KeyBytes[0]=$this->PKV_GetKeyByte($Seed, 24, 3, 200);
         $KeyBytes[1]=$this->PKV_GetKeyByte($Seed, 10, 0, 56);
         $KeyBytes[2]=$this->PKV_GetKeyByte($Seed, 1, 2, 91);
         $KeyBytes[3]=$this->PKV_GetKeyByte($Seed, 7, 1, 100);

Ora questa parte scritta in PHP crea un codice che comunico (tramite mail automatica) all'interessato.

Ora toccherà al programma (scritto in Lazarus) elaborare questa informazione, e io ho scritto una libreria per fare questo:

[code]

unit MySerialNumber;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils;

  const
  KEY_GOOD = 0;
  KEY_INVALID = 1;
  KEY_BLACKLISTED = 2;
  KEY_PHONY = 3;

  type
      SerialNumber=object
      private
      public
            function PKV_GetKeyByte(const Seed : Int64; a, b, c : Byte) : Byte;
            function PKV_CheckKey(const S : String) : Integer;
            function PKV_CheckKeyChecksum(const Key : String) : Boolean;
            function PKV_MakeKey(const Seed : Int64) : String;
            function PKV_GetChecksum(const s : String) : String;
      end;
var
                BL : array[0..0] of String = ('11111111');
implementation

{ serial number }
function StartsStr(str: string; inizio: string): boolean;
var
    Esci: boolean;
    ret: boolean;
    i: integer;
    len1: integer;
    len2: integer;
begin
    len1:=length(str);
    len2:=length(inizio);
    ret:=false;
    if len1>=len2 then
    begin
        i:=0;
        ret:=TRUE;
        if len1=0 then
            Esci:=TRUE
        else
            Esci:=FALSE;
        while (Esci=False) do
        begin
            if str[i]<>inizio[i] then
            begin
                Esci:=TRUE;
                ret:=FALSE;
            end;
            Inc(i);
            if i>len1 then
                Esci:=TRUE;
        end;
    end;
    StartsStr:=ret;
end;

function SerialNumber.PKV_GetKeyByte(const Seed : Int64; a, b, c : Byte) : Byte;
var
   risultato: byte;
begin
  a := a mod 25;
  b := b mod 3;
 if a mod 2 = 0 then
    risultato := ((Seed shr a) and $000000FF) xor ((Seed shr b) or c)
  else
    risultato := ((Seed shr a) and $000000FF) xor ((Seed shr b) and c);
    PKV_GetKeyByte:=risultato;
end;

function SerialNumber.PKV_GetChecksum(const s : String) : String;
var
  left, right, sum : Word;
  i : Integer;
  app: string;
begin
  left := $0056;
  right := $00AF;
if Length(s) > 0 then
    for i := 1 to Length(s) do
    begin
      right := right + Byte(s[i]);
      //app:= app + 'r: ' + s[i] + '(' + IntToStr(Byte(s[i])) + ')';
      //right := right + Byte(s[i]);
      if right > $00FF then
        Dec(right, $00FF);
      Inc(left, right);
      if left > $00FF then
        Dec(left, $00FF);
    end;
  sum := (left shl 8) + right;
  result := IntToHex(sum, 4);
end;

function SerialNumber.PKV_MakeKey(const Seed : Int64) : String;
var
  KeyBytes : array[0..3] of Byte;
  i : Integer;
  app: string;
begin
  // Fill KeyBytes with values derived from Seed.
  // The parameters used here must be extactly the same
  // as the ones used in the PKV_CheckKey function.
  // A real key system should use more than four bytes.
  KeyBytes[0] := PKV_GetKeyByte(Seed, 24, 3, 200);
  KeyBytes[1] := PKV_GetKeyByte(Seed, 10, 0, 56);
  KeyBytes[2] := PKV_GetKeyByte(Seed, 1, 2, 91);
  KeyBytes[3] := PKV_GetKeyByte(Seed, 7, 1, 100);
   // the key string begins with a hexidecimal string of the seed
  result := IntToHex(Seed, 8);
// then is followed by hexidecimal strings of each byte in the key
  for i := 0 to 3 do
  begin
    result := result + IntToHex(KeyBytes[i], 2);
  end;
// add checksum to key string
  result := result + PKV_GetChecksum(result);
// Add some hyphens to make it easier to type
  i := Length(result) - 3;
  while (i > 1) do
  begin
    Insert('-', result, i);
    Dec(i, 4);
  end;
end;

function SerialNumber.PKV_CheckKeyChecksum(const Key : String) : Boolean;
var
  s, c : String;
begin
  result := False;
 // remove cosmetic hypens and normalize case
  s := UpperCase(StringReplace(Key, '-', '', [rfReplaceAll]));
  if Length(s) <> 20 then
    exit; // Our keys are always 20 characters long
  // last four characters are the checksum
  c := Copy(s, 17, 4);
  SetLength(s, 16);
// compare the supplied checksum against the real checksum for
  // the key string.
  result := c = PKV_GetChecksum(s);
end;


function SerialNumber.PKV_CheckKey(const S : String) : Integer;
var
  Key, kb : String;
  Seed : Int64;
  i : Integer;
  b : Byte;
begin
  result := KEY_INVALID;
  if not PKV_CheckKeyChecksum(S) then
    exit; // bad checksum or wrong number of characters
 // remove cosmetic hypens and normalize case
  Key := UpperCase(StringReplace(S, '-', '', [rfReplaceAll]));
 // test against blacklist
  if Length(BL) > 0 then
    for i := Low(BL) to High(BL) do
      if StartsStr(BL[i], Key) then
      begin
        result := KEY_BLACKLISTED;
        exit;
      end;
// At this point, the key is either valid or forged,
  // because a forged key can have a valid checksum.
  // We now test the "bytes" of the key to determine if it is
  // actually valid.
// When building your release application, use conditional defines
  // or comment out most of the byte checks!  This is the heart
  // of the partial key verification system. By not compiling in
  // each check, there is no way for someone to build a keygen that
  // will produce valid keys.  If an invalid keygen is released, you
  // simply change which byte checks are compiled in, and any serial
  // number built with the fake keygen no longer works.
// Note that the parameters used for PKV_GetKeyByte calls MUST
  // MATCH the values that PKV_MakeKey uses to make the key in the
  // first place!
result := KEY_PHONY;
 // extract the Seed from the supplied key string
  if not TryStrToInt64('$' + Copy(Key, 1, 8), Seed) then
    exit;
{$IFDEF KEY00}
  kb := Copy(Key, 9, 2);
  b := PKV_GetKeyByte(Seed, 24, 3, 200);
  if kb <> IntToHex(b, 2) then
    exit;
  {$ENDIF}
{$IFDEF KEY01}
  kb := Copy(Key, 11, 2);
  b := PKV_GetKeyByte(Seed, 10, 0, 56);
  if kb <> IntToHex(b, 2) then
    exit;
  {$ENDIF}
  {$IFDEF KEY02}
  kb := Copy(Key, 13, 2);
  b := PKV_GetKeyByte(Seed, 1, 2, 91);
  if kb <> IntToHex(b, 2) then
    exit;
  {$ENDIF}
  {$IFDEF KEY03}
  kb := Copy(Key, 15, 2);
  b := PKV_GetKeyByte(Seed, 7, 1, 100);
  if kb <> IntToHex(b, 2) then
    exit;
  {$ENDIF}
 // If we get this far, then it means the key is either good, or was made
  // with a keygen derived from "this" release.
result := KEY_GOOD;
end;

end.


[/code]

Quello che è importante è che i valori numerici della funzione PKV_GetKeyByte siano valorizzati in maniera identica con quelli del codice PHP

  KeyBytes[0] := PKV_GetKeyByte(Seed, 24, 3, 200);
  KeyBytes[1] := PKV_GetKeyByte(Seed, 10, 0, 56);
  KeyBytes[2] := PKV_GetKeyByte(Seed, 1, 2, 91);
  KeyBytes[3] := PKV_GetKeyByte(Seed, 7, 1, 100);


Per poter sfruttare questa libreria bastano poche linee di codice in free pascal

     if length(Codice)=24 then
     begin
          Valore:=MioOggetto.PKV_CheckKey(Codice);
          if Valore=0 then
          begin

                 {CODICE DI ATTIVAZIONE VALIDO}
          end;
     end;

Dove la variabile Codice è valorizzata con il codice che precedentemente avevamo comunicato al nostro cliente.

Bene questa è la soluzione che avevo usato io in uno dei miei progetti. Se avete altre soluzioni non esitate a comunicarmele e vedrò di pubblicarle. Avverto che pubblicherò solo soluzioni che possono essere multipiattaforma.

Share on Twitter! Digg this story! Del.icio.us Share on Facebook! Technorati Reddit StumbleUpon

20 Ott 2011 - File INI

Spesso può capitare che all'avvio di un software si necessiti di caricarsi dei dati, per esempio i dati di connessione ad un DB. Per fare questo ci vengono in aiuto i comodissimi file INI.


Un file ini è un semplice file di testo che finisce con estensione ini, ed è strutturato per sezioni, facciamo l'esempio di aver la necessità di caricare i dati per la connessione al database e i dati di altre configurazioni (lingua, versione, email,...).


Il file ini incriminato dovrebbe essere così strutturato

[ConnDB]

Host=localhost

Nick=pippo

Pwd=pluto

DBFile=c:\appoggio.s3db

[Altro]

Lingua=italiano

Ver=1.0

Questo file va salvato in C:\ con il nome Config.ini per poter essere coerente con l'esempio successivo.

Il programma che andrebbe a leggere questi dati dovrebbe essere così strutturato:


Program Project1;

 
{$mode objfpc}{$H+}
 
Uses

  Classes,SysUtils

  ,INIFiles {libreria per usare i file ini}

  ;

 
Var
 INI:TINIFile;
 Nick,Pwd,Host,DBFile, Lingua,Versione:String;
begin
  INI := TINIFile.Create('C:\Config.ini');

  Nick := INI.ReadString('ConnDB','Nick','');

  Pwd := INI.ReadString('ConnDB','Pwd','');

  Host := INI.ReadString('ConnDB','Host','');

  DBFile := INI.ReadString('ConnDB','DBFile','');

Lingua := INI.ReadString('Altro','Lingua','');

  Versione:= INI.ReadString('Altro','Ver','');

  Ini.Free; // After we used ini file, we must call the Free method of object

  {Faccio qualcosa con questi dati}

  ...

end.    

Come vedete è parecchio semplice usare i file ini nei propri progetti. Ovviamente non è il massimo lasciare in chiaro le password nei file ini, ma l'esempio sopra voleva essere semplice. In un prossimo how to spieghero come usare le funzioni crittografiche di Lazarus/Free Pascal, e con quelle nozioni capirete come ovviare al problema delle password in chiaro nei file INI.

 
Share on Twitter! Digg this story! Del.icio.us Share on Facebook! Technorati Reddit StumbleUpon
Pagine: 1 ... 11 12 [13] 14