Annunci

Linkedin


Appunti di programmazione su Delphi in Italiano

Questo blog non vuole essere o sostituirsi ad una guida per il linguaggio delphi, ma essere solo una raccolta di esempi che ho raccolto e commentato in italiano negli anni trascorsi a programmare con questo linguaggio. Alcuni di questi esempi saranno corredati di codice sorgente, altri solamente di commenti e piccole spiegazioni. Sperando che possa essere d'aiuto a qualcun altro. Saluti a tutti, Eric.
martedì, ottobre 25, 2011 @ 01:10 PM admin

Il sensore di prossimità è posizionato nella parte superiore del monitor, la sua funzione è rilevare una vicinanza, ad esempio quella della faccia durante una chiamata, e disattivare il monitor per evitare di premere erroneamente dei tasti. Attivare il sensore di prossimità (Sensor Proximity) è molto semplice, basta inserire questa riga di codice:

{$IFDEF FPC}
UIDevice.CurrentDevice.setProximityMonitoringEnabled(true);
{$ENDIF}

ricordatevi ovviamente di inserire “iphoneall” nella Uses…

mercoledì, settembre 28, 2011 @ 11:09 AM admin

Questo week-end ho scaricato dal sito della Embarcadero il nuovo Rad Studio XE2 in versione di prova. Devo ammettere che ci sono molte novità interessanti e tra queste l’introduzione di Firemonkey e quindi la possibilità di creare con il nostro Delphi applicazioni per Mac OSX e IOS. A parte testare gli esempi inclusi, la prima cosa che ho fatto è provare la connessione ad un database locale, condizione minima e necessaria per sviluppare una qualsiasi app che non sia una calcolatrice. Il risultato è stato alquanto deludente, i componenti e le classi dei db non funzionano su IOS. Questo pone una grossa limitazione, così ho provato a creare una piccola app di test e a modificare il codice da XCode (che in questo caso utilizza FPC) e da lì sono riuscito a connettermi ad un database di SQLite. uses

… SQLite3db,SQLite;

….

function TBBSqlite.GetTable(sql:string): TBBTable;
var
table1: TBBTable;
i1,i2:integer;
{$IFDEF MSWINDOWS}
sltb: TSQLIteTable;
{$ELSE}
QryResult,RecResult  : Classes.TStringList;
{$ENDIF }
begin
{$IFDEF MSWINDOWS}
sltb := fdb.GetTable(sql);
try
if not (sltb.EOF)then
table1:=TBBtable.Create(sltb.RowCount,sltb.ColCount)
else
table1:=TBBtable.Create(0,0);
for i1:=0 to sltb.RowCount-1 do
begin
for i2:=0 to sltb.ColCount-1 do
begin
table1.setvalue(i1,i2,sltb.Fields[i2]);
end;
sltb.Next;
end;
finally
Result:=table1;
end;
{$ELSE}
QryResult := Classes.TStringList.Create;
RecResult := Classes.TStringList.Create;
RecResult.Delimiter := ‘,’;
RecResult.QuoteChar := ‘”‘;
RecResult.StrictDelimiter := True;
if fdb.Query(sql,QryResult) then
begin
for i1 := 0 to QryResult.Count-1 do
begin
RecResult.DelimitedText:=QryResult[i1];
if i1=0 then
table1:=TBBTable.Create(QryResult.Count,RecResult.Count);
for i2 := 0 to RecResult.Count-1 do
begin
table1.setvalue(i1,i2,RecResult[i2]);
end;
end;
Result:=table1;
end;
{$ENDIF }
end;

var

QryResult,RecResult  : Classes.TStringList;

fdb:TSQLiteDatabase;

begin

QryResult := Classes.TStringList.Create

fdb:=TSQLite.Create(Filename);

if fdb.Query(sql,QryResult) then

begin

for i1 := 0 to QryResult.Count-1 do

begin

….

end;

end;

end;

giovedì, febbraio 24, 2011 @ 03:02 PM admin

This feature allows you to retrieve the default language set on the system, consists of two functions: GetSystemDefaultLangID that returns the binary Language identifier in Microsoft Word format (eg 1040 for Italy) and function VerLanguageName that retrieves the description of the language associated with the binary Microsoft language identifier.

function recupera_lingua: string;

var

lingua: array [0..50] of char;

begin

VerLanguageName(GetSystemDefaultLangID,lingua, 50);

Result := StrPas(Lang_array);

end;

Compatible with:

  • Windows XP: SI
  • Windows VISTA: SI
  • Windows 7: TO VERIFY
giovedì, febbraio 24, 2011 @ 03:02 PM admin

This feature allows you to retrieve the default language set on the system, consists of two functions: GetSystemDefaultLangID that returns the binary Language identifier in Microsoft Word format (eg 1040 for Italy) and function VerLanguageName that retrieves the description of the language associated with the binary Microsoft language identifier.

function recupera_lingua: string;

var

lingua: array [0..50] of char;

begin

VerLanguageName(GetSystemDefaultLangID,lingua, 50);

Result := StrPas(Lang_array);

end;

Compatible with:

  • Windows XP: SI
  • Windows VISTA: SI
  • Windows 7: TO VERIFY
mercoledì, febbraio 23, 2011 @ 02:02 PM admin

La funzione API ShellExecute può lanciare un’applicazione o aprire un file in ambiente WIN32. E’ utile in molte situazioni in quanto evita di scrivere molte righe di codice per raggiungere lo stesso scopo come ad esempio inviare una e-mail (es. Inviare E-Mail con ShellExecute).

HINSTANCE ShellExecute(HWND hwnd, LPCTSTR lpOperation, LPCTSTR lpFile, LPCTSTR lpParameters, LPCTSTR lpDirectory, nShowCmd);

Parametri:

  • hwnd: handle della finistra, questo valore può essere NULL se la chiamata non è associata a nessuna finestra
  • lpOperation: è una Pchar che contiene l’azione da eseguire, le azioni più comuni sono
    • edit: lancia l’editor e apre il relativo documento settato in lpFile all’interno dell’editor
    • explore: esplora una cartella specificata in lpFile
    • find: cerca nella directory specificata in lpDirectory
    • open: apre la voce specificata in lpFile
    • print: stampa un file specificato in lpFile, se quest’ultimo non è un file la funzione dà errore
  • lpFile: Pchar contenente il nome del file o dell’oggetto che deve essere eseguito a seconda di lpOperation
  • lpParameters: Pchar contenente i parametri che devono essere passati all’applicazione. Se lpFile è un documento deve essere impostata a NULL
  • lpDirectory: Pchar che deve contenere la directory di lavoro, se è NULL prende il valore dell’attuale directory di lavoro
  • nShowCmd: flag che specifica come deve essere visualizzata l’applicazione quando si apre, può assumere i seguenti valori: SW_HIDE,SW_MAXIMIZE,SW_MINIMIZE,SW_RESTORE, SW_SHOW, SW_SHOWDEFAULT, SW_SHOWMAXIMIZED, SW_SHOWMINIMIZED, SW_SHOWMINNOACTIVE, SW_SHOWNA, SW_SHOWNOACTIVATE, SW_SHOWNORMAL

Valore restituito (intero):

  • 0 (zero):  errore di memora o di risorsa del S.O.
  • ERROR_FILE_NOT_FOUND: il file specificato non esite
  • ERROR_PATH_NOT_FOUND: il percorso specificato non esiste
  • ERROR_BAD_FORMAT: il file eseguibile non è valido
  • SE_ERR_ACCESSDENIED: il sistema operativo nega l’accesso al file
  • SE_ERR_ASSOCINCOMPLETE: il file associato è incompleto o non è valido
  • SE_ERR_DDEBUSY: la transazione DDE non può essere completata perché altre transazioni DDE sono in fase di elaborazione
  • SE_ERR_DDEFAIL: transazione DDE fallita
  • SE_ERR_DDETIMEOUT: transazione DDE non completata perchè la richiesta è andata fuori tempo limite
  • SE_ERR_DLLNOTFOUND: la DLL specificata non è stata trovata
  • SE_ERR_FNF: il file specificato non è stato trovato
  • SE_ERR_NOASSOC: nessuna applicazione è associata al file specificato
  • SE_ERR_OOM: memoria insufficiente per completare l’operazione
  • SE_ERR_PNF: la directory specificata non è stata trovata
  • SE_ERR_SHARE: violazione della condivisione

Ora vediamo alcuni esempi pratici dell’utilizzo della funzione ShellExecute

Lanciare un’applicazione

ShellExecute(Handle, ‘open’, PChar(’c:\delphi\delphi.exe’), nil, nil, SW_SHOW);

Aprire un file nel Blocco note

ShellExecute(Handle, ‘open’, PChar(’notepad’), PChar(’c:\test\readme.txt’), nil, SW_SHOW);

Stampare un documento

ShellExecute(Handle, ‘print’, PChar(’c:\test\test.doc’), nil, nil, SW_SHOW);

Aprire una pagina web

ShellExecute(Handle, ‘open’, PChar(’http://www.delphi-blog.it/’), nil, nil, SW_SHOW);

Esplorare una directory

ShellExecute(Handle, ‘explore’, PChar(’c:\windows)’, nil, nil, SW_SHOW);

Avviare un comando dal prompt di DOS:

ShellExecute(Handle, ‘open’, PChar(’command.com’), PChar(’/c copy file1 file2′), nil, SW_SHOW);

Aprire il client di posta predefinito per inviare una mail

ShellExecute(0, ‘open’,’mailto:info@delphi-blog.it’, nil, nil, SW_SHOWNORMAL);

mercoledì, febbraio 23, 2011 @ 10:02 AM admin

Creare una mail ed inviarla tramite il proprio client di posta diventa semplicissimo nel momento in cui usiamo la funzione API ShellExecute. Il più grosso vantaggio evidente di questa tecnica è il non dover occuparsi direttamente dell’invio in quanto la API aprirà direttamente la mail creata nel client di posta predefinito. Gli svantaggi potrebbero essere il non poter allegare documenti, non poter mettere immagini nel testo se non caricate tramite un link html, l’invio non è automatico ma bisogna dare al client di posta la conferma all’invio.

uses ShellApi;

procedure TForm1.sendClick(Sender: TObject);
var
pch:Pchar;
begin
pch:=pchar(’mailto:’+toemail.Text+’?subject=’+subject.Text+’&body=’+body.Text);
ShellExecute(0, ‘open’,pch, nil, nil, SW_SHOWNORMAL);
end;

procedure TForm1.sendClick(Sender: TObject);

var

pch:Pchar;

begin

pch:=pchar(’mailto:’+toemail.Text+’?subject=’+subject.Text+’&body=’+body.Text);

ShellExecute(0, ‘open’,pch, nil, nil, SW_SHOWNORMAL);

end;

Con MS-Outlook è anche possibile inserire degli allegati, la stringa in questo caso diventa:

mailto:info@microsoft.com?Subject=subject_Text&Body=body_Text&&Attach=”c:\Delphi_Mail_Attachments\attachment.txt”

Se il client di posta non si dovesse aprire (esempio: Windows Vista con Windows Mail) è necessario entrare in pannello di controllo fare l’associazione.

Pannello di controllo->Programmi predefiniti->Associa un tipo di file a un programma->Associare MAILTO a Windows Mail

Potete scaricare i sorgenti e l’eseguibile di esempio da qui: Send_Email_API

Compatibile con:
  • Windows XP: SI
  • Windows VISTA: SI
venerdì, dicembre 10, 2010 @ 10:12 AM admin

Per riprodurre un file audio di tipo wav utiliamo una API molto immediata inclusa nella unit MMSystem:

BOOL PlaySound(pszSound:PAnsiChar; hmod: Cardinal; fdwSound: Cardinal);


Descrizione dei parametri

pszSound : stringa che specifica il suono da riprodurre. Se diamo a questo parametro NULL tutte le riproduzioni wav si fermano.

hmod: Handle dell’eseguibile che contiene la risorsa da caricare.

fdwSound: flags che può assumere i seguenti valori

SND_APPLICATION: The sound is played using an application-specific association.

SND_ALIAS: The pszSound parameter is a system-event alias in the registry or the WIN.INI file. Do not use with either SND_FILENAME or SND_RESOURCE.

SND_ALIAS_ID:  The pszSound parameter is a predefined sound identifier.

SND_ASYNC: The sound is played asynchronously and PlaySound returns immediately after beginning the sound. To terminate an asynchronously played waveform sound, call PlaySound with pszSound set to NULL.

SND_FILENAME: The pszSound parameter is a filename.

SND_LOOP: The sound plays repeatedly until PlaySound is called again with the pszSound parameter set to NULL. You must also specify the SND_ASYNC flag to indicate an asynchronous sound event.

SND_MEMORY:  A sound event’s file is loaded in RAM. The parameter specified by pszSound must point to an image of a sound in memory.

SND_NODEFAULT: No default sound event is used. If the sound cannot be found, PlaySound returns silently without playing the default sound.

SND_NOSTOP: The specified sound event will yield to another sound event that is already playing. If a sound cannot be played because the resource needed to generate that sound is busy playing another sound, the function immediately returns FALSE without playing the requested sound.
If this flag is not specified, PlaySound attempts to stop the currently playing sound so that the device can be used to play the new sound.

SND_NOWAIT: If the driver is busy, return immediately without playing the sound.

SND_PURGE: Sounds are to be stopped for the calling task. If pszSound is not NULL, all instances of the specified sound are stopped. If pszSound is NULL, all sounds that are playing on behalf of the calling task are stopped.
You must also specify the instance handle to stop SND_RESOURCE events.

SND_RESOURCE: The pszSound parameter is a resource identifier; hmod must identify the instance that contains the resource.

SND_SYNC: Synchronous playback of a sound event. PlaySound returns after the sound event completes.

Esempio:

uses
MMSystem;

//Riproduzione singola

procedure TForm1.Button1.Click;
begin
PlaySound(’c:\eric.wav’, 0, SND_FILENAME + SND_ASYNC);
end;

//Riproduzione in loop

procedure TForm1.Button2.Click;
begin
PlaySound(’c:\eric.wav’, 0, SND_LOOP + SND_ASYNC);
end;

//Stop del loop

procedure TForm1.Button3.Click;
begin
PlaySound(nil, 0, 0);
end;

Compatibile con:

  • Windows XP: SI
  • Windows VISTA: SI
  • Windows 7: DA VERIFICARE
venerdì, luglio 16, 2010 @ 04:07 PM admin

Questa funzione permette di recuperare la lingua di default impostata sul sistema, si compone di due funzioni: GetSystemDefaultLangID che restituisce il binary Microsoft language identifier in formato word (es. 1040 per italia) e della funzione VerLanguageName che recupera la descrizione della lingua associata al binary Microsoft language identifier.

function recupera_lingua: string;

var

lingua: array [0..50] of char;

begin

VerLanguageName(GetSystemDefaultLangID,lingua, 50);

Result := StrPas(Lang_array);

end;

Compatibile con:

  • Windows XP: SI
  • Windows VISTA: SI
  • Windows 7: DA VERIFICARE
domenica, novembre 8, 2009 @ 08:11 PM admin

Una modalità molto semplice per sfruttare SAPI (Speech API).  Da me utilizzata per dare il buongiorno al caricamento dell’applicazione o in particolari situazioni dove l’utente pilota ad esempio una pistola per codice a barre e il programma gli torna lo stato di quel prodotto nel magazzino.

Includiamo anzitutto la unit Comobj:

uses Comobj;

E ora il semplice codice da inserire per ottenere la lettura della nostra stringa:

var

voce: OLEVariant;

begin

voce := CreateOLEObject(’SAPI.SpVoice’);

voce.Speak(’Ciao Mondo!’, 0);

end;

Veramente immediato. Ovviamente questo semplice codice legge nella lingua di default del motore text-to-speech installato. Prossimamente vedremo come utilizzare la voce italiana.

Compatibile con:
  • Windows XP: SI
  • Windows VISTA: SI
  • Windows 7: DA VERIFICARE
venerdì, novembre 6, 2009 @ 09:11 AM admin

Per recuperare il nome della stampante di default possiamo utilizzare l’oggetto printer. Innanzitutto c’è dobbiamo includere la unit “printers”.

unit printers;

E recuperiamo il nome nel seguente modo:

Printer.PrinterIndex := -1;
NomeStampanteDefault := Printer.Printers.Strings[Printer.PrinterIndex];

Compatibile con:
  • Windows XP: SI
  • Windows VISTA: SI
  • Windows 7: DA VERIFICARE