Tips&Tricks | I trucchi del mestiere |
![]() |
Come convertire una stringa in maiuscoletto |
<% '---- 'Funzione Maiuscoletto ' 'la stringa strSource passata alla 'funzione CCase verrα convertita 'in maiuscoletto ' 'Massimiliano Luciani 'webmaster@byluciani.com 'http://www.byluciani.com '---- Function CCase(strSource) Dim arrWords Dim i If IsNull(strSource) Or Len(Trim(strSource)) < 1 Then CCase = strSource Else strSource = LCase(strSource) arrWords = Split(strSource) For i = 0 To UBound(arrWords) arrWords(i) = UCase(Left(arrWords(i), 1)) & Mid(arrWords(i), 2) Next CCase = Join(arrWords) End If End Function 'str = "Un TIP per convertire una stringa in " & _ ' "maiuscoletto - Massimiliano Luciani - byluciani.com" str=" d " Response.Write "Origine: " & str Response.Write " |
![]() |
Come monitorare un file o una cartella di sistema |
Imports System Imports System.Diagnostics Imports System.IO Imports System.Threading Public Class Form1 Inherits System.Windows.Forms.Form Private Allarme As System.IO.FileSystemWatcher Private InfoFile As FileInfo #Region " Codice generato da Progettazione Windows Form " àààààààà #End Region Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click AddHandler Allarme.Changed, AddressOf Cambiamento AddHandler Allarme.Renamed, AddressOf Rinomina Allarme.EnableRaisingEvents = True End Sub Private Sub Cambiamento(ByVal Sorgente As Object, ByVal e As FileSystemEventArgs) MsgBox("Attenzione il file Φ cambiato in qualche sua componente") End Sub Private Sub Rinomina(ByVal Sorgente As Object, ByVal e As System.IO.RenamedEventArgs) MsgBox("Attenzione il file Φ stato Rinominato") End Sub Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Allarme = New FileSystemWatcher() InfoFile = New FileInfo("c:\test.txt") With Allarme .Path = InfoFile.DirectoryName.ToString .Filter = "" .NotifyFilter = NotifyFilters.FileName Or _ NotifyFilters.Size Or NotifyFilters.LastWrite Or NotifyFilters.CreationTime End With End Sub End Class |
![]() |
Come leggere lo stato del CAPS LOCK |
function IsCapsLockOn : boolean; begin Result := 0 <> (GetKeyState(VK_CAPITAL) and $01); end; |
![]() |
Come spostare il focus all'oggetto successivo o precedente |
SelectNext(ActiveControl as TWinControl,True,True ); |
SelectNext(ActiveControl as TWinControl,False,True ); |
![]() |
Come ricavare il nome della window posizionata in una specifica posizione dello schermo |
function NomeWindow( X, Y : integer ) : string; var P : TPoint; W : TWinControl; begin P.X := X; P.Y := Y; W := FindVCLWindow( P ); if( nil <> W )then begin Result := W.Name; end else begin Result := ''; end; end; |
![]() |
Come mappare l'hard-disk |
DWORD WNetAddConnection2( LPNETRESOURCE lpNetResource, LPCTSTR lpPassword, LPCTSTR lpUsername, DWORD dwFlags ); Function MappaDischi(LocalUnit, UserN, PassW: String): boolean; var NRW: NetResource; Res: DWORD; begin Result := False; NRW.dwType := RESOURCETYPE_DISK; NRW.lpLocalName := PChar(LocalUnit + ':'); NRW.lpRemoteName := PChar('\\indirizzoIP\D$'); NRW.lpProvider := ''; Res = WNetAddConnection2(NRW, PChar(PassW), PChar(UserN), CONNECT_UPDATE_PROFILE) Result := (Res <> NO_ERROR) If Not Result Then ShowMessage('Non Φ possibile eseguire la mappatura); end; |
![]() |
Come leggere la data dell'ultimo accesso ad un file |
function Ultimoaccesso(sFileName : string ) : TDateTime; var ffd : TWin32FindData; dft : DWord; lft : TFileTime; h : THandle; begin h := Windows.FindFirstFile(PChar(sFileName), ffd); if (INVALID_HANDLE_VALUE <> h) then begin Windows.FindClose( h ); FileTimeToLocalFileTime(ffd.ftLastAccessTime, lft ); FileTimeToDosDateTime(lft,LongRec(dft).Hi, LongRec(dft).Lo); Result := FileDateToDateTime(dft); end; end; |
![]() |
Come chiedere conferma per la chiusura di una applicazione |
procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin if(mrNo = MessageDlg('Sei sicuro di voler terminare il programma?'', mtInformation,[mbYes, mbNo],0)) then begin CanClose := False; end; end; |
![]() |
Aprire e chiudere il carrello del lettore del CD |
Procedure ApriCD; Begin mciSendString('Set cdaudio door open', nil, 0, 0); End; Procedure ChiudiCD; Begin mciSendString('Set cdaudio door closed', nil, 0, 0); End; |
![]() |
Inviare una e-mail con il programma di posta elettronica predefinito |
ShellExecute(Handle, 'open', 'mailto: GiuseppeSgro@email.it?subject=mail', '', '', SW_SHOWDEFAULT); |
![]() |
Lanciare il browser predefinito ed aprire una pagina web |
ShellExecute(Handle, 'open', 'http://www.delphitips.com', '', '', SW_SHOWDEFAULT); |
![]() |
Come convertire un carattere nel suo corrispondente codice ascii |
Label1.Caption:='Il codice ASCII del carattere "A" Φ ' + IntToStr(ord('A')); Label2.Caption:='Il carattere corripondente al codice ASCII 65 Φ' + chr(65); |
![]() |
Lanciare un'applicazione ed attenderne la fine dell'esecuzione |
procedure Esempio; var ProgramHandle : THandle; begin ProgramHandle := WinExec('C:\Programma.exe', SW_SHOWNORMAL); while GetModuleusage(ProgramHandle) <> 0 do application.processmessages; {Tutto ci≥ che verrα iserito qui sarα eseguito finchΦ non termina l'applicaizone esegiuta da winexec} end; |
![]() |
Usare cut & paste in Java |
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); String str = textarea.getText(); StringSelection contents = new StringSelection(str); cb.setContents(contents, null); |
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable content = cb.getContents(this); try { String str = (String)content.getTransferData(DataFlavor.stringFlavor); textarea.setText(str); } catch (Throwable e) { System.err.println(e); } |
![]() |
Concatenazione di stringhe e performance |
String string1 = "Ciao "; String string2 = "Federico"; string1 = string1 + string2; |
StringBuffer buffer1 = "Ciao "; String string2 = "Federico"; buffer1.append(string2); |
![]() |
Pass-by-Value e Pass-By-Reference |
void passByValue(int i) { f = 15; } void passByReference(StringBuffer sb) { sb.append(" vedo?"); } void provaMetodi() { int i = 1; StringBuffer sb = new StringBuffer("Cosa"); passByValue(i); passByReference(sb); System.out.println("Value of i: " + i); System.out.println("Value of sb: " + sb); } |
Value of i: 1 Value of sb: Cosa vedo? |
![]() |
La corto-circuitazione degli operatori booleani |
if ( object != null && object.equalsTo(otherObject) ) { // fai qualcosa con object } |
![]() |
Thread ed eccezioni |
public void uncaughtException(Thread t, Throwable e) |
Thread(ThreadGroup tg, Runnable target, String name) Thread(ThreadGroup tg, Runnable target) Thread(ThreadGroup tg, String name) |
![]() |
Internazionalizzare le applicazioni |
NumberFormat nf2 = NumberFormat.getInstance(Locale.ITALIAN); System.out.println(nf2.format(1234.56)); |
1.234,56 |
![]() |
Classi interne e classi anonime |
class UnaClasseNormale { void unMetodo() {} void unAltroMetodo() {} } class UnAltraClasseNormale { // Queste due classi saranno visibili solo in UnAltraClasseNormale static class UnaClasseInterna {} // classe interna statica class AltraClasseInterna {} // classe interna void unMioMetodo() { class ClasseInternaLocale {} // classe interna locale al metodo } void mioAltroMetodo() { // classe anonima: ridefinisce un metodo della classe originale UnaClasseNormale bref = new UnaClasseNormale () { void unMetodo() {} // Qui ridefinisco il metodo originale }; } } |
![]() |
Come dichiarare array anonimi |
myMethod(new int[] {10, 23, 45, 9, 12, 59}); // dichiarazione di myMethod: void myMethod(int[] values) |
![]() |
Gestire le versioni dei package |
Manifest-Version: 1.0 Name: it/fedmest/myclasses Specification-Title: Java Package con Versioni Specification-Vendor: Federico Mestrone Specification-Version: 1.0 Implementation-Title: it.fedmest.myclasses Implementation-Vendor: FedericoMestrone.Com Implementation-Version: Build 1.0.3-b32 |
Package pkg = Package.getPackage("it.fedmest.myclasses"); System.out.println("Package name:\t" + pkg.getName()); System.out.println("Spec title:\t" + pkg.getSpecificationTitle()); System.out.println("Spec vendor:\t" + pkg.getSpecificationVendor()); System.out.println("Spec version:\t" + pkg.getSpecificationVersion()); System.out.println("Impl title:\t" + pkg.getImplementationTitle()); System.out.println("Impl vendor:\t" + pkg.getImplementationVendor()); System.out.println("Impl version:\t" + pkg.getImplementationVersion()); |
![]() |
Realizzare un file Zip in Java |
BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream("D:\\filezippato.zip"); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); out.setMethod(ZipOutputStream.DEFLATED); // Attiva la compressione byte data[] = new byte[2048]; FileInputStream fi = new FileInputStream("D:\\filenormale.doc"); origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry("D:\\filenormale.doc"); out.putNextEntry(entry); int count; while((count = origin.read(data, 0, 2048)) != -1) { out.write(data, 0, count); } origin.close(); out.close(); |
![]() |
ZipAnywhere: WinZip secondo Java |
![]() |
Memoria a disposizione |
Runtime rt = Runtime.getRuntime(); System.out.println("Memoria totale massima a disposizione della VM: " + rt.totalMemory()); System.out.println("Memoria ancora non utilizzata di quella a disposizione: " + rt.freeMemory()); |
![]() |
Come ricavare la versione del programma sviluppato |
Il codice che segue permette di ricavare la versione del programma, le stesse informazioni visualizzate dal menu proprietà di un file Windows.
Me.Caption = Me.Caption &App.Major & "." & App.Minor & "." & App.Revision |
![]() |
Convertire in modo semplice un file grafico da WMF a BMP |
Private Sub Command1_Click() ' Legge il file WMF Prova dal disco e: Picture1.Picture = LoadPicture("e:\prova.wmf") ' Salva nella stessa directory il corrispondente file in formato BMP SavePicture Picture1.Image, "" End Sub |
![]() |
Spostare un file su disco |
Name "C:\MIOFILE.TXT" As "C:\COPIA\MIOFILE.TXT" |
Invece di rinominare il file il risultato sarà lo spostamento in un'altra directory.
![]() |
Controllare se un form Φ presente in memoria |
Private Function CercaForm(ByVal form_name As String) As Form Dim i As Integer ' Per default la form non e' trovata. Set CercaForm = Nothing ' Ciclo per la ricerca. For i = 0 To Forms.Count - 1 If Forms(i).Name = form_name Then ' We found it. Return this form. Set CercaForm = Forms(i) Exit For End If Next i End Function |
![]() |
Accettare solo caratteri numerici all'interno di una textbox |
Private Sub Text1_Change() If Not IsNumeric(Text1.Text) Then Text1.Text = "" End If |
![]() |
Come rilevare una connessione internet attiva |
Private Declare Function InternetGetConnectedState Lib "wininet" (ByRef dwflags As Long,ByVal dwReserved As Long) As Long |
Con queste costanti
possiamo anche distinguere il tipo di connessione attiva.
Private Const CONNECT_LAN As Long = &H2 Private Const CONNECT_MODEM As Long = &H1 Private Const CONNECT_PROXY As Long = &H4 Private Const CONNECT_OFFLINE As Long = &H20 |
Il codice che segue
illustra un possibile uso della funzione in oggetto.
Public Function IsWebConnected(Optional ByRef ConnType As String) As Boolean Dim dwflags As Long Dim WebTest As Boolean ConnType = "" WebTest = InternetGetConnectedState(dwflags, 0&) Select Case WebTest Case dwflags And CONNECT_LAN: ConnType = "LAN" Case dwflags And CONNECT_MODEM: ConnType = "Modem" Case dwflags And CONNECT_PROXY: ConnType = "Proxy" Case dwflags And CONNECT_OFFLINE: ConnType = "Offline" End Select IsWebConnected = WebTest End Function Private Sub Command1_Click() Dim msg As String If IsWebConnected(msg) Then msg = "Sei connesso ad internet tramite : " & msg Else msg = "Non sei connesso ad internet." End If MsgBox msg, vbOKOnly, "Stato della connessione ad internet" End Sub |
![]() |
Come rilevare il tipo di unitα fornita come parametro |
Declare Function GetDriveType Lib "kernel32" Alias "GetDriveTypeA" (ByVal nDrive As String) As Long |
![]() |
Rilevare lo spazio disponibile su un disco e altre informazioni |
Private Declare Function GetDiskFreeSpace Lib "kernel32" Alias "GetDiskFreeSpaceA" (ByVal lpRootPathName As String, lpSectorsPerCluster As Long, lpBytesPerSector As Long, lpNumberOfFreeClusters As Long, lpTtoalNumberOfClusters As Long) As Long |
![]() |
Conoscere la dimensione in byte di un file |
Dimensione=FileLen("c:\miofile.txt ") |
![]() |
Come rilevare il nome del computer in uso |
Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long Function Nomepc() As String Dim ls_Mach As String Dim ll_MachLen As Long ll_MachLen = 16 ls_Mach = String$(ll_MachLen, 0) If GetComputerName(ls_Mach, ll_MachLen) Then Nomepc = Left$(ls_Mach, ll_MachLen) End Function |
![]() |
Nascondere il puntatore del mouse |
Declare Function ShowCursor& Lib "user32" (ByVal bShow As Long) |
ShowCursor 0 ' nasconde il puntatore ShowCursor 1 ' riattiva la visualizzazione del puntatore |
![]() |
Come generare codici alfanumerici univoci |
Option Explicit Private Declare Function CoCreateGuid Lib "ole32.dll" (pguid As Guid) AsLong Private Declare Function StringFromGUID2 Lib "ole32.dll" (rguid As Any, ByVal lpstrClsId As Long, ByVal cbMax As Long) As Long Private Type Guid Data1 As Long Data2 As Long Data3 As Long Data4(8) As Byte End Type Public Function CreateGUID() As String Dim udtGUID As Guid Dim strGUID As String Dim bytGUID() As Byte Dim lngLen As Long Dim lngRetVal As Long Dim lngPos As Long lngLen = 40 bytGUID = String(lngLen, 0) CoCreateGuid udtGUID lngRetVal = StringFromGUID2(udtGUID, VarPtr(bytGUID(0)), lngLen) strGUID = bytGUID If (Asc(Mid$(strGUID, lngRetVal, 1)) = 0) Then lngRetVal = lngRetVal - 1 End If strGUID = Left$(strGUID, lngRetVal) CreateGUID = strGUID End Function Public Function CreateID() As String CreateID = RemoveChars(CreateGUID, "{-}") End Function Private Function RemoveChars(Source As String, Chars As String) As String Dim enumChars As Long RemoveChars = Source For enumChars = 1 To Len(Chars) RemoveChars = Replace(RemoveChars, Mid(Chars, enumChars, 1), "") Next End Function Sub main() MsgBox CreateID() End Sub |