Annunci

Linkedin


Posts Tagged ‘api’

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
mercoledì, novembre 4, 2009 @ 01:11 PM admin

Per recuperare il time-out dello screensaver utilizziamo la API SystemParametersInfo che il sistema ci mette a disposizione.

function ScreenSaverTimeout: Integer;

begin

SystemParametersInfo(SPI_GETSCREENSAVETIMEOUT, 0, @Result, 0);

end;

La funzione restituisce il time-out espresso in secondi.

Compatibile con:
  • Windows XP: SI
  • Windows VISTA: SI
martedì, novembre 3, 2009 @ 02:11 PM admin

Per contare le linee di scroll della rotella del mouse utilizziamo l’API SystemParametersInfo già usata in altri appunti. Di seguito una funzione che restituisce il numero di linee:

function GETWHEELSCROLLLINES: Integer;

begin

SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, @Result, 0);

end;

Se restituisce -1 dovrebbe essere impostato per lo scroll dell’intera pagina.

Compatibile con:
  • Windows XP: SI
  • Windows VISTA: SI
domenica, novembre 1, 2009 @ 07:11 PM admin

Questa funzione permette di invertire i pulsanti del mouse:

SystemParametersInfo(SPI_SETMOUSEBUTTONSWAP, 1, nil, 0);

Per far tornare invece i pulsanti allo stato originale:

SystemParametersInfo(SPI_SETMOUSEBUTTONSWAP, 0, nil, 0);

Ho utilizzato questa funzione una sola volta in quanto si rischia di confondere l’utente, soprattutto se non si prevedono tutte le casistiche, ad esempio nell’eventualità di un errore che chiude l’applicazione in modo inaspettato i pulsanti rimangono invertiti. Il seguito ve lo faccio immaginare.

Comunque è possibile chiamare l’API SystemParametersInfo per impostare e ottenere tutte le impostazioni controllate dal Pannello di controllo di Windows. Nei prossimi appunti vedremo come.