Tips&Tricks | I trucchi del mestiere |
![]() |
Un cattura schermo facile facileà |
using System; using System.Drawing; using System.Runtime.InteropServices; class CatturaSchermo { [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hdcDst, int xDst, int yDst, int cx, int cy, IntPtr hdcSrc, int xSrc, int ySrc, uint ulRop); public static void Main(string[] args) { string filename=@"C:\cattura.bmp"; if(args.Length>0) filename=args[0]; Graphics gfxScreen = Graphics.FromHwnd(IntPtr.Zero); Bitmap bmp = new Bitmap((int) gfxScreen.VisibleClipBounds.Width, (int) gfxScreen.VisibleClipBounds.Height, gfxScreen); Graphics gfxBitmap = Graphics.FromImage(bmp); IntPtr hdcScreen = gfxScreen.GetHdc(); IntPtr hdcBitmap = gfxBitmap.GetHdc(); BitBlt(hdcBitmap, 0, 0, bmp.Width, bmp.Height, hdcScreen, 0, 0, 0x00CC0020);//costante SRCCOPY gfxBitmap.ReleaseHdc(hdcBitmap); gfxScreen.ReleaseHdc(hdcScreen); gfxBitmap.Dispose(); gfxScreen.Dispose(); bmp.Save(filename); } } |
csc cattura.cs |
cattura.exe [percorsofile.bmp] |
![]() |
Come reperire informazioni utili utilizzando il registro di sistema |
procedure TForm1.FormCreate(Sender: TObject); var reg : tregistry; s :string; i :integer; begin Reg := TRegistry.Create ; Reg.RootKey :=HKEY_CURRENT_USER; if reg.OpenKey('Software\Microsoft\Active Setup\Installed Components\{44BBA840-CC51-11CF-AAFA-00AA00B6015C}',false )then begin s:=reg.ReadString('Username'); l.Items.Add('Nome Utente = '+s); end; Reg := TRegistry.Create ; Reg.RootKey :=HKEY_CURRENT_USER; // if reg.OpenKey('Software\Microsoft\Windows\ShellNoRoam',false )then begin s:=reg.ReadString(''); l.Items.Add('Nome Compuiter = '+s); end; Reg := TRegistry.Create ; Reg.RootKey :=HKEY_LOCAL_MACHINE; // if reg.OpenKey('HARDWARE\DESCRIPTION\System\CentralProcessor\0',false )then begin s:=reg.ReadString('ProcessorNameString'); l.Items.Add('Processore = '+s); end; Reg := TRegistry.Create ; Reg.RootKey :=HKEY_LOCAL_MACHINE; // if reg.OpenKey('HARDWARE\DESCRIPTION\System\CentralProcessor\0',false )then begin s:=reg.ReadString('Identifier'); l.Items.Add('Identificazione = '+s); end; Reg := TRegistry.Create ; Reg.RootKey :=HKEY_LOCAL_MACHINE; // if reg.OpenKey('HARDWARE\DESCRIPTION\System\CentralProcessor\0',false )then begin i:=reg.Readinteger('~MHz'); l.Items.Add('Velocitα CPU = '+inttostr(i)+' MHz'); end; Reg := TRegistry.Create ; Reg.RootKey :=HKEY_USERS; // if reg.OpenKey('S-1-5-21-1220945662-1454471165-725345543-1003\Software\Liter\SystemInfo\BIOS',false )then begin s:=reg.ReadString('Product'); l.Items.Add('Nome Bios = '+s); end; Reg := TRegistry.Create ; Reg.RootKey :=HKEY_USERS; // if reg.OpenKey('S-1-5-21-1220945662-1454471165-725345543-1003\Software\Liter\SystemInfo\BIOS',false )then begin s:=reg.ReadString('Date'); l.Items.Add('Data = '+s); end; Reg := TRegistry.Create ; Reg.RootKey :=HKEY_USERS; // if reg.OpenKey('S-1-5-21-1220945662-1454471165-725345543-1003\Software\Liter\SystemInfo\Mainboard',false )then begin s:=reg.ReadString('Current'); l.Items.Add('Nome scheda madre = '+s); end; //ed eccetera................ end; |
![]() |
Gestione avanzata eccezioni! |
/** * Classe dÆutilitα per uso dei TryMethodsà */ public class ExceptionUtil { private ExceptionUtil() {} public static Object execute(TryMethod method,java.util.Collection args){ try { return method.execute(args); }catch (Exception ex) { return ex; } } }//end /** * Interfaccia che stabilisce il contratto di un TryMethod da implementare per le * RuntimeExceptionà */ public interface TryMethod{ public Object execute(java.util.Collection args); } /** * Implementazione di TryMethod per le checked exceptionà */ public class ReflectiveMethod implements TryMethod{ private Object target; private String methodName; private Class[] paramTypes; public void init(Object target, String methodName, Class [] paramTypes){ this.target = target; this.methodName = methodName; this.paramTypes = paramTypes; } public Object execute(java.util.Collection args){ try { Class clazz = target instanceof Class?(Class)target:target.getClass(); return (clazz.getDeclaredMethod(methodName,paramTypes)).invoke( (target instanceof Class?null:target),args.toArray()); }catch (java.lang.reflect.InvocationTargetException iex){return iex.getTargetException();}catch (Exception ex) {return ex;} } }//end |
![]() |
Un semplice blocco note |
import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; public class BloccoNotes implements WindowListener, ActionListener{ //Istanze della classe private Frame finestra; private TextArea areaTesto; //Costruttore della classe public BloccoNotes(Frame f, TextArea t) { finestra = f; areaTesto = t; } //Gestione della grafica // Metodi non implementati dell'interfaccia WindowListener public void windowActivated(WindowEvent evt) {} public void windowDeactivated(WindowEvent evt) {} public void windowDeiconified(WindowEvent evt) {} public void windowIconified(WindowEvent evt) {} public void windowOpened(WindowEvent evt) {} // Metodi implementati dell'interfaccia WindowListener public void windowClosed(WindowEvent evt) { System.exit(0); } public void windowClosing(WindowEvent evt) { finestra.dispose(); } // Metodo acoltatore ha il computo di ascoltare i comandi public void actionPerformed(ActionEvent evt) { String comando = evt.getActionCommand(); //gestione dei vari eventi if (comando.equals("Esci")) { finestra.dispose(); } else if (comando.equals("Apri")) { areaTesto.setText(""); FileDialog d = new FileDialog(finestra, "Apri documento", FileDialog.LOAD); d.setVisible(true); if (d.getFile() != null) { try { String line; BufferedReader in = new BufferedReader(new FileReader(d.getDirectory() + File.separator + d.getFile())); while ((line = in.readLine()) != null) areaTesto.append(line + "\n"); } catch (Exception e) { System.out.println("Errore: " + e); } } } else if (comando.equals("Salva con nome...")) { FileDialog d = new FileDialog(finestra, "Salva documento con nome", FileDialog.SAVE); d.setVisible(true); PrintWriter fout; String Stringa=areaTesto.getText(); try{ fout=new PrintWriter(new FileWriter(d.getDirectory()+File.separator+d.getFile())); StringTokenizer st=new StringTokenizer(Stringa,"\n"); //E' importante per gestire la pressione dell'invio while (st.hasMoreTokens()) fout.println(st.nextToken()); fout.close(); }catch(Exception e){} } } /** Metodo Main */ public static void main(String[] args) { Frame f = new Frame("My blocco note "); TextArea t = new TextArea(); BloccoNotes n = new BloccoNotes(f, t); MenuBar mb = new MenuBar(); // Preparazione men∙ file il menu File Menu menu = new Menu("File"); mb.add(menu); menu.add("Apri"); menu.add("Salva con nome..."); menu.addSeparator(); menu.add("Esci"); menu.addActionListener(n); // Prepara la finestra f.addWindowListener(n); f.setMenuBar(mb); f.add(t); f.setSize(400, 500); f.setVisible(true); } } // BloccoNotes |
![]() |
Connessioni JDBC condivise |
![]() |
Ordinare un array bidimensionale |
import java.io.PrintStream; public class Ordinamento { public Ordinamento() { nome = new String[5][4]; nome[0][0] = "Rossi Paolo "; nome[0][1] = "Garibaldi n\260 34 "; nome[0][2] = "Roma "; nome[0][3] = "00100 "; nome[1][0] = "Rossi Mario "; nome[1][1] = "Mazzini n\260 14 "; nome[1][2] = "Milano "; nome[1][3] = "20100 "; nome[2][0] = "Rossi Francesca "; nome[2][1] = "Napoleone n\260 121 "; nome[2][2] = "Milano "; nome[2][3] = "20100 "; nome[3][0] = "Rossi Giovanni "; nome[3][1] = "Lincolm n\260 12 "; nome[3][2] = "Torino "; nome[3][3] = "10100 "; nome[4][0] = "Rossi Alberto "; nome[4][1] = "Cattaneo n\260 176 "; nome[4][2] = "Bologna "; nome[4][3] = "40100 "; System.out.println(" SCRITTURA DISORDINATA ALFABETICAMENTE"); System.out.println(" "); System.out.println("Cognome e nome Via Citt\340 C.A.P. "); System.out.println(" "); for(x = 0; x < 5; x++) { System.out.println(" "); for(j = 0; j < 4; j++) System.out.print(nome[x][j]); } for(int i = nome.length - 1; i >= 0; i--) { for(int k = 1; k <= i; k++) if(nome[k][0].compareTo(nome[k - 1][0]) < 0) { nomeb = new String[5]; for(int l = 0; l < 4; l++) { nomeb[l] = nome[k - 1][l]; nome[k - 1][l] = nome[k][l]; nome[k][l] = nomeb[l]; nomeb[l] = ""; } } } System.out.println(" "); System.out.println(" "); System.out.println(" "); System.out.println(" SCRITTURA ORDINATA ALFABETICAMENTE"); for(x = 0; x < 5; x++) { System.out.println(" "); for(j = 0; j < 4; j++) System.out.print(nome[x][j]); } } public static void main(String args[]) { Ordinamento ordinamento = new Ordinamento(); } int x; int j; String nome[][]; String nomeb[]; } |
![]() |
Passare valori tra pagine web |
function leggivariabile(variabile) { // variabile contiene il nome della variabile var indirizzo = window.location.toString() + "&"; // indirizzo contiene l'indirizzo della pagina nella forma // "indirizzo?variabile1=valore1&variabile2=valore2&variabile3=valore3&" var posizionenome=indirizzo.indexOf(variabile + "="); // trova la posizione in cui e' memorizzata la variabile if (posizionenome==-1) return ""; // se restituisce -1 la variabile non c'e'! :( var sottostringa=indirizzo.substring(posizionenome); // taglia tutto quello che c'e' prima della variabile var inizio=sottostringa.indexOf("="); // trova l'uguale dopo il quale si trova il valore var fine=sottostringa.indexOf("&"); // trova la & che indica dove finisce il valore var variabile=sottostringa.substring(inizio + 1, fine); // assegna a variabile il valore contenuto tra = e &! return variabile; } |
![]() |
Passare valori tra pagine web |
import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*; import javax.swing.text.*; import javax.swing.text.rtf.*; /** * Titolo: RTFView * Descrizione: Visualizza RTF in pagine Web * @author Gianluca Esposito (giaesp@tiscali.it) * @version 0.11.17.03 */ public class RTFView extends JApplet { private boolean isStandalone = false; JScrollPane rtfScroller = new JScrollPane(); JTextPane rtfPane = new JTextPane(); String RTFText; int bground; public String getParameter(String key, String def) { return isStandalone ? System.getProperty(key, def) : (getParameter(key) != null ? getParameter(key) : def); } public RTFView() { } public void init() { try { RTFText = this.getParameter("RTF", "Nessuna informazione da visualizzare."); } catch (Exception e) { e.printStackTrace(); } try { bground = Integer.parseInt(this.getParameter("bground", "FFFFFF"), 16); } catch (Exception e) { e.printStackTrace(); } try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { // this.setSize(new Dimension(width,height)); rtfPane.setEditorKit(new RTFEditorKit()); rtfPane.setEditable(false); rtfPane.setCaretPosition(0); rtfPane.setText(RTFText); // Inserimento del testo RTF this.getContentPane().add(rtfScroller, BorderLayout.CENTER); rtfScroller.getViewport().add(rtfPane, null); rtfPane.setBackground(new Color(bground)); rtfScroller.setBackground(new Color(bground)); this.setVisible(true); } public void start() { } public void stop() { } public void destroy() { } public String getAppletInfo() { return "RTFView 0.11.17.03 (Gianluca Esposito - giaesp@tiscali.it)"; } public String[][] getParameterInfo() { String[][] pinfo = { { "RTF", "String", "Corpo dell'RTF"}, { "bground", "hex int", "Colore di sfondo - Inserire sequenza esadecimale (come nell'HTML, ma senza \"#\")"}, }; return pinfo; } static { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { } } } |
![]() |
Acquisire immagini tramite scanner |
Private Sub Form_Load() Command1.Caption = "Scannerizza!" Label1.Caption = "Staus: none" End Sub Private Sub Command1_Click() ' scanner pronto? ImgScan1.ScannerAvailable ' apre la porta dello scanner ImgScan1.OpenScanner ' inizia la scansione ImgScan1.StartScan End Sub Private Sub ImgScan1_PageDone(ByVal PageNumber As Long) Label1.Caption = "status: page " & PageNumber & " done." 'salva l'immagine al percorso specificato ImgEdit1.SaveAs "c:\provascan.jpg", 6 End Sub Private Sub ImgScan1_ScanDone() Label1.Caption = "status: scan done." End Sub Private Sub ImgScan1_ScanStarted() Label1.Caption = "status: scan started." End Sub |
![]() |
Una console per le vostre applicazioni |
Private Declare Function AllocConsole Lib "kernel32" () As Long Private Declare Function FreeConsole Lib "kernel32" () As Long Private Declare Function CloseHandle Lib "kernel32" (ByVal handleObj As Long) As Long Private Declare Function GetStdHandle Lib "kernel32" (ByVal handle As Long) As Long Private Declare Function WriteConsole Lib "kernel32" Alias "WriteConsoleA" _ (ByVal hConsoleOutput As Long, lpBuffer As Any, ByVal _ nNumberOfCharsToWrite As Long, lpNumberOfCharsWritten As Long, _ lpReserved As Any) As Long Private Const STD_OUTPUT_HANDLE = -11& Dim hConsole As Long Private Sub btnTest_Click() Dim retCode As Long, stdOut As String, byteScritti As Long stdOut = vbCrLf & "Grazie per aver provato !!!" & vbCrLf retCode = WriteConsole(hConsole, ByVal stdOut, Len(stdOut), byteScritti, ByVal 0&) Shell App.Path & "\TEST.BAT" End Sub Private Sub Form_Load() hConsole = IstanziaConsole End Sub Private Sub Form_Unload(Cancel As Integer) RilasciaConsole hConsole End Sub Function IstanziaConsole() As Long IstanziaConsole = 0 If AllocConsole() Then IstanziaConsole = GetStdHandle(STD_OUTPUT_HANDLE) If IstanziaConsole = 0 Then MsgBox "Impossibile reindirizzare l'output sulla Console", vbOKOnly + vbCritical End If Else MsgBox "Impossibile aprire la Console", vbOKOnly + vbCritical End If End Function Function RilasciaConsole(handleConsole As Long) CloseHandle handleConsole FreeConsole End Function |
![]() |
Un semplice autocomplete dei form di IE |
Option Explicit Private winTitolo As String 'Verifico se l'oggetto passatomi e' un campo di tipo password Private Function IsPasswordBox(Elemento As Object) As Boolean On Error GoTo err_password If LCase(Elemento.getAttribute("Type")) = "password" Then IsPasswordBox = True Else IsPasswordBox = False End If Exit Function err_password: IsPasswordBox = False End Function 'Verifico se il campo e' una text box Private Function IsTextBox(Elemento As Object) As Boolean On Error GoTo err_text If LCase(Elemento.getAttribute("Type")) = "text" Then IsTextBox = True Else IsTextBox = False End If Exit Function err_text: IsTextBox = False End Function Private Function CercaCampi(Documento As Object) As Boolean Dim Elemento As Object Dim numOggetti As Long Dim indiceOggetti As Long Dim Trovato As Boolean Dim ok As Integer 'Prendo il numero degli oggetti nel documento numOggetti = Documento.All.length 'Scorro gli elementi fino a trovarne uno di tipo password o text For indiceOggetti = 0 To numOggetti - 1 DoEvents Set Elemento = Documento.All.Item(indiceOggetti) 'Verifico se e' una password-box e la riempio con la parola pluto If IsPasswordBox(Elemento) Then 'Il false serve per rendere case-insensitive la ricerca dell'attributo value ok = Elemento.setAttribute("Value", "pluto", False) Trovato = True End If 'Verifico se e' una text-box e la riempio con la parola paperino If IsTextBox(Elemento) Then 'Il false serve per rendere case-insensitive la ricerca dell'attributo value ok = Elemento.setAttribute("Value", "paperino", False) Trovato = True End If Next numOggetti = Documento.frames.length 'Eseguo la verifica anche su eventuali frame nella pagina For indiceOggetti = 0 To numOggetti - 1 'Esegui la ricerca anche in questi frame If CercaCampi(Documento.frames.Item(indiceOggetti).document) Then Trovato = True Next CercaCampi = Trovato End Function Private Sub Scansiona() Dim objShellWins As New SHDocVw.ShellWindows Dim objExplorer As SHDocVw.InternetExplorer Dim Documentoument As HTMLDocument Dim Trovato As Boolean Dim Eseguito As Boolean Screen.MousePointer = vbHourglass 'Scorri tutte le fineste aperte For Each objExplorer In objShellWins If TypeOf objExplorer.document Is HTMLDocument Then Set Documentoument = objExplorer.document 'Salva il titolo cosi' da poterle riconoscere winTitolo = Documentoument.Title 'Comincia la ricerca nel documento Eseguito = CercaCampi(Documentoument) If Eseguito Then Trovato = True End If Next Screen.MousePointer = vbDefault End Sub Private Sub cmdPasswords_Click() Scansiona End Sub |
![]() |
Salvare un grafico MSChart come immagine |
Public Sub SalvaMSChart(Graph As MSChart, pic As PictureBox, ByVal FileName As String) 'Copia il grafico nella clipboard Graph.EditCopy ' Imposta la picture della PicBox pic.Picture = Clipboard.GetData(vbCFMetaFile) ' Salva l'immagine SavePicture pic.Picture, FileName End Sub |