Delphi Basic Development Skills (2)
◇ [DELPHI] How to calculate a size of the directory function GetDirectorySize (const ADirectory: string): Integer; varDir: TSearchRec; Ret: integer; Path: string; beginResult: = 0; Path: = ExtractFilePath (ADirectory); Ret: = Sysutils .FIRECST (ADIRECTORY, FAANYFILE, DIR); if Ret <> NO_ERROR THEN EXIT; TryWHILE RET = NO_ERROR DOBEGININC (Result, Dir.size); if (Dir.attr In [fadirectory]) and (dir.name [1] < > '.') Theninc (Result, getDirectorySize (Path Dir.name '/*.*'): r = sysutils.findnext (dir); end; finallysysutils.FindClose (Dir); end; end; ◇ [DELPHI] How to add the installer to the Uninstall list operation registry, as follows: 1. Create a primary key under the hkey_local_machine / currentVersion / Uninstall key, name is arbitrary. Example HKEY_LOCAL_MACHINE / SOFTWARE / Microsoft / Windows / CurrentVersion / Uninstall / MyUninstall2 in HKEY_LOCAL_MACHINE / SOFTWARE / Microsoft / Windows / CurrentVersion / Uninstall / MyUnistall two string values under the key, the two string value of the name is specific: DisplayName and UninstallString . 3. Give a DISPLAYNAME assignments to the name in the "Delete Application List", such as 'aIming Uninstall One'; assigning the delete commands executed by the strey uninstallString, such as c: /win97/uninst.exe -f "C: /TestPro/aimTest.isu"◇[DELPHI] WM_QUERYENDSESSION shutdown message intercepted typeTForm1 = class (TForm) procedure WMQueryEndSession (var message: TWMQueryEndSession); message WM_QUERYENDSESSION; procedure CMEraseBkgnd (var message: TWMEraseBkgnd); message WM_ERASEBKGND; private {Private declarations} public {public declarations} end; procedure TForm1.WMQueryEndSession (var Message: TWMQueryEndSession); beginShowmessage ( 'computer is about to shut down'); end; ◇ [DELPHI] Get Network neighborhood procedure getnethood (); // NT server to do, Win98 is debugged.
vara, i: integer; errcode: integer; netres: array [0..1023] of netresource; enumhandle: thandle; enumentries: dword; buffersize: dword; s: string; mylistitems: tlistitems; mylistitem: tlistitem; alldomain: tstrings; begin // listcomputer is a listview to list all computers; controlcenter is a form.alldomain: = tstringlist.Create; with netres [0] do begindwscope: = RESOURCE_GLOBALNET; dwtype: = RESOURCETYPE_ANY; dwdisplaytype: = RESOURCEDISPLAYTYPE_DOMAIN; dwusage: = RESOURCEUSAGE_CONTAINER; lplocalname: = nil; lpremotename: = nil; lpcomment: = nil; lpprovider: = nil; end; // get all fields errcode: = wnetopenenum (RESOURCE_GLOBALNET, RESOURCETYPE_ANY, RESOURCEUSAGE_CONTAINER, @ netres [0], enumhandle); if errcode = NO_ERROR then beginenumentries: = 1024; buffersize: = sizeof (netres); errcode: = wnetenumresource (enumhandle, enumentries, @ netres [0], buffersize); end; a: = 0; mylistitems: = controlcenter.lstcomputer.Items; MYLISTITEMS.CLEAR; while (Netres [a] .lpprovider <> ') AND (errcode = no_error) dobeginaldomain.add (NetRes [a] .lpremotename); A: = a 1; end; WnetClo seenum (enumhandle); // get all computers mylistitems: = controlcenter.lstcomputer.Items; mylistitems.Clear; for i: = 0 to alldomain.Count-1 dobeginwith netres [0] do begindwscope: = RESOURCE_GLOBALNET; dwtype: = RESOURCETYPE_ANY ; dwdisplaytype: = RESOURCEDISPLAYTYPE_SERVER; dwusage: = RESOURCEUSAGE_CONTAINER; lplocalname: = nil; lpremotename: = pchar (alldomain [i]); lpcomment: = nil; lpprovider: = nil; end; ErrCode: = WNetOpenEnum (RESOURCE_GLOBALNET, RESOURCETYPE_ANY, RESOURCEUSAGE_CONTAINER, @Netres [0], enumhandle; if errcode = no_error dameginenumentries: = 1024; buffersize: = sizeof (Netres); errcode: =
WneetenumResource (EnumHandle, ENUMENTRIES, @ NetRes [0], Buffersize; end; A: = 0; while (string (netres [a] .lpppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppProiStitem: = myListItems.Add MyListItem.imageIndex: = 0; MyListItem.caption: = Uppercase (StringReplace (StringReplace (String (Netres [a] .lpremotename), '//', '', [RFREPLACEALL]); A: = A 1; END; wnetcloseenum (enumhandle); end; end; ◇ [DELPHI] Gets procedure getsharefolder shared directory on a computer (const computername: string); varerrcode, a: integer; netres: array [0..1023] of netresource; enumhandle: thandle; enumentries, buffersize: dword; s: string; mylistitems: tlistitems; mylistitem: tlistitem; mystrings: tstringlist; beginwith netres [0] do begindwscope: = RESOURCE_GLOBALNET; dwtype: = RESOURCETYPE_DISK; dwdisplaytype: = RESOURCEDISPLAYTYPE_SHARE; dwusage: = RESOURCEUSAGE_CONTAINER; lplocalname: = nil; lpremotename: = pchar (computername); lpcomment: = nil; lpprovider: = nil; end; // Get the root errcode: = wnetopenenum (RESOURCE_GLOBALNET, RESOURCETYPE_DISK, RESOURCEUSAGE_CONTAINER, @ netres [0], enumhandle) If errcode = no_ERROR THENBEGINENUMEN tries: = 1024; BufferSize: = SizeOf (NetRes); ErrCode: = WNetEnumResource (EnumHandle, EnumEntries, @ NetRes [0], BufferSize); end; wnetcloseenum (enumhandle); a: = 0; mylistitems: = controlcenter.lstfile. Items; mylistitems.Clear; while (string (netres [a] .lpprovider) <> '') and (errcode = NO_ERROR) dobeginwith mylistitems dobeginmylistitem: = add; mylistitem.ImageIndex: = 4; mylistitem.Caption: = extractfilename (netres [A] .lpremotename; end; a: = a 1; end; end; ◇ [delphi] gets hard disk serial number var Serialnum: pdword; A, B: DWORD; buffer: array [0..255] of char Begin if getVolumeInformation ('c: /'
, Buffer, Sizeof (Buffer), Serialnum, A, B, NIL, 0) THEN Label1.caption: = INTOSTR (Serialnum ^); End; ◇ [Delphi] MEMO automatic page flooding Procedure ScrollMemo (Memo: TMEMO; Direction: char); begin case direction of 'd': begin SendMessage (Memo.Handle, {HWND of the Memo Control} WM_VSCROLL, {Windows Message} SB_PAGEDOWN, {Scroll Command} 0) {Not Used} end; 'u': begin SendMessage (Memo.Handle, {HWND of the Memo Control} WM_VSCROLL, {Windows Message} SB_PAGEUP, {Scroll Command} 0); {Not Used} end; end; end; procedure TForm1.Button1Click (Sender: TObject); begin ScrollMemo (Memo1, 'D'); // Turn page End; Procedure TFORM1.BUTTON1CLICK (Sender: Tobject); Begin ScrollMemo (Memo1, 'u'); // Turn the page END; ◇ [Delphi] DBGRID to the next position (Tab key) procedure TForm1.DBGrid1KeyPress (Sender: TObject; var key: Char); beginif key = # 13 thenif DBGrid1.Columns.Grid.SelectedIndex
◇ [DELPHI] directory completely removed (deltree) procedure TForm1.DeleteDirectory (strDir: String); var sr: TSearchRec; FileAttrs: Integer; strfilename: string; strPth: string; begin strpth: = Getcurrentdir (); FileAttrs: = faAnyFile; IF FindFirst (StrPth '/' strdir '/ *. *', FileAtTRS, SR) = 0 THEN BEGIN IF (sr.attr and fileattrs) = sr.attr the begin strfilename: = sr.name; if FileExists (StrPth ) / ' strdir ' / ' strfilename) Then Deletefile (StrPth ' / ' strdir ' / ' strfilename); end; while findnext (sr) = 0 do begin if (sr.attr and fileattrs) = sr.attr THEN begin strfilename: = sr.name; if fileexists (strpth '/' strdir '/' strfilename) then deletefile (strpth '/' strdir '/' strfilename); end; end; FindClose (sr); removedir ( Strpth '/' strdir); end; end; ◇ [Delphi] gets the current cursor of the TMEMO control. Row and column information to TPOINT 1.Function ReadCursorpos (SourceMemo: TMEMO): TPOINT; VAR POINT: TPOINT; Begin Point: : = SendMessage (SourceMemo.handle, EM_LineFromchar, SourceMemo.selstart, 0); Point.x: = SourceMemo.selstart-sendMessage (SourceMemo.handle, EM_LINEINDEX, POINT.Y, 0); RESULT: = POINT; END; 2.LineLength: = SendMessage (Memol. Handle, EM-LINELENGTH, CPOS, 0); // President [Delphi] Read hard disk serial number function getDiskSerial (Diskcha: char): string; varserialnum: pdword; A, B: DWORD; buffer: array [0 .. 255] OF CHAR; BeginResult: = ""; if GetVolumeInformation (Pchar (Diskcha ": /"), Buffer, Sizeof (Buffer), Serialnum, A, B, NIL, 0) THEN Result: = INTOSTR (Serialnum ^); END; ◇ [Internet] CSS common comprehensive skills 1. P: first-letter {font-size: 300%; float: Left} // The first word will increase three times more than ordinary fonts. 2. / / Connect an external style sheet 3. Embed a style sheet
4. // Inline style arial // span accepts style, class, and id attribute DIV can include paragraphs, titles, tables, and even other parts
5. Class attribute // Definition See 3.6. ID attribute
// Definition See 3.7. Property list font style: font-style: [Normal | Italic | Oblique]; font size: font-size: [xx-small | x-small | small | Medium | Large | X-Large | XX-Large | Larger | Smaller |
Length unit relative units: EM (EM, element font) EX (X-height, letter "x" height) PX (pixel, resolution relative to the screen) absolute length: in (inch, 1 inch = 2.54 Cm) cm (cm, 1 cm = 10 mm) mm (m) PT (point, 1 point = 1/72 inches) PC (Pa, 1 Pa = 12 points) ◇ [Delphi] VCL production brief steps 1. Create parts Attribute method events (establish library units, inherited to new types, add attributes, methods, events, registration parts, build package files) 2. Message processing 3. Exception processing 4. Parts Visual ◇ [Delphi] Dynamic connection library Static loading: procedure name; external 'lib.dll'; dynamic loading: Var Handle: Thandle; Handle: = loadingLibrary ('lib.dll'); if Handle <> 0 thenbegin {dosomething} freeelibrary (handle); end; [Delphi] Pointer variable and address var x, y: integer; p: ^ integer; / / pointing to the integer variable pointer x: = 10; // Variable assignment P: = @ x; // Variable x address y: = P ^; / / For y assignment pointer p @@ procedure // Return process variable memory address ◇ [Delphi] judgment character is a character of Chinese characters ByType ('Hello Haha', 1) = MBLEADBYTE / / is the first Character ByType ('Hello Haha', 2) = MBTRAILBYTE / / is the second character ByType ('Hello Haha', 5) = MBSINGLEBYTE / / Not Chinese characters ◇ [Delphi] MEMO positioning operation MEMO1. LINES.DELETE (0) // Delete Line 1 Memo1.selStart: = 10 // Positioning 10 bytes ◇ [Delphi] Get Double-byte Characters Function Getit (S: String): Integer; BeginResult: = Byte (s [1]) * $ 100 byte (s [2]); end; use: getit (') // $ BCC6, 10 refine 48326 ◇ [Delphi] calling the add data stored procedure stored procedure as follows: Create Procedure AddRecord (Record1 Varchar (10) Record2 Varchar (20)) AsbeginInsert Into Tabl ename (field1, field2) values (: record1,: record2) end execute a stored procedure: EXECUTE procedure addrecord ( "urrecord1", "urrecord2") ◇ [DELPHI] to save the file to the blob field function blobcontenttostring (const filename: string) : string; beginwith tfilestream.create (filename, fmopenread) dotrysetlength (Result, size); read (Pointer (Result) ^, size); finallyfree; end; end; // save field beginif (opendialog1.execute) thenbeginsFileName: = OpenDialog1 .Filename; adotable1.edit; adotable1.fieldbyname ('visio'). Asstring: = blobcontentTostring (filename); adotable1.post; end; ◇ [Delphi] copy all files to clipboard Uses shlobj, ActiveX, Clipbrd;
procedure Tform1.copytoclipbrd (var FileName: string); varFE: TFormatEtc; Medium: TStgMedium; dropfiles: PDropFiles; pFile: PChar; beginFE.cfFormat: = CF_HDROP; FE.dwAspect: = DVASPECT_CONTENT; FE.tymed: = TYMED_HGLOBAL; Medium. hGlobal: = GlobalAlloc (GMEM_SHARE or GMEM_ZEROINIT, SizeOf (TDropFiles) length (FileName) 1); if Medium.hGlobal <> 0 then beginMedium.tymed: = TYMED_HGLOBAL; dropfiles: = GlobalLock (Medium.hGlobal); trydropfiles ^. Pfiles: = SizeOf (TDROPFILES); Dropfiles ^ .fwide: = false; longint (pfile): = longint (drop refiles) sizeof (TDROPFILES); STRPCOPY (Pfile, FileName); Inc (Pfile, Length (filename) 1) ; pFile ^: = # 0; finallyGlobalUnlock (Medium.hGlobal); end; Clipboard.SetAsHandle (CF_HDROP, Medium.hGlobal); end; end; ◇ [DELPHI] include the currently running process uses TLHelp32; procedure TForm1.Button1Click (Sender : TObject); var lppe: TProcessEntry32; found: boolean; Hand: THandle; beginHand: = CreateToolhelp32Snapshot (TH32CS_SNAPALL, 0); found: = Process32First (Hand, lppe); while found dobeginListBox1.Items.Add (StrPas (lppe.szExeFile )) ;fact: = proce ss32Next (Hand, lppe); end; end; ◇ [DELPHI] The establishment of a new table BDETable1 Table2Table2: = TTable.Create (nil); tryTable2.DatabaseName: = Table1.DatabaseName; Table2.FieldDefs.Assign (Table1.FieldDefs); Table2.indexdefs; table2.tablename: = 'new_table'; table2.createTable (); finallytable2.free (); end; ◇ [delphi] Most food understanding DLL establishment and reference // First look at DLL first Source (File -> New -> DLL) library project1; usessysUtils, classes; function addit (f: integer; s: integer): integer; enginmakeasure; = f s; end; exportsaddit; end; Call (in Ur Project) IMPLEMentationFunction Addit (f: integer; s: integer): Integer; Far; External 'Project1'; // Declining {call is Addit (2, 4);
The result is displayed 6} ◇ [Delphi] Dynamic Reader Size Function Gesselfsize: Integer; VARF: File of Byte; BeginFileMode: = 0; AssignFile (f, Application.exename); reset (f); result: = filesis (f); ); // unit is byte closefile (f); end; ◇ [delphi] read BIOS information with memo1.lines do begin add ('mainboardbiosname:' ^ i string (PCHAR (Ptr (PTR ($ FE061)))) ); Add ('mainboardbioscopyright:' ^ i string (PCHAR (Ptr ($ FE091))))))); add ('mainboardbiosdate:' ^ i string (PCHAR (Ptr (PTR ($ FFF5)))); Add ( 'MainBoardBiosSerialNo:' ^ I string (Pchar (Ptr ($ FEC71)))); end; ◇ [DELPHI] MSSQL alias is dynamically established procedure TForm1.Button1Click (Sender: TObject); var MyList: TStringList; beginMyList: = TStringList .Create; Trywith MyList DobeGinAdd ('Server Name = 210.242.86.2'); add ('database name = db'); add ('user name = sa'); end; session1.addalias ('testsql', 'mssql' , MyList); // Chemie MSSQLSession1.SaveConfigFile; finallyMyList.Free; Session1.Active: = True; Database1.DatabaseName: = 'DB'; Database1.AliasName: = 'TESTSQL'; Database1.LoginPrompt: = False Database1.Params.Add ('user name = sa'); Database1.Params.Add ('password ='); Database1.connected: = T rue; end; end; procedure TForm1.Button2Click (Sender: TObject); beginDatabase1.Connected: = False; Session1.DeleteAlias ( 'TESTSQL'); end; ◇ [DELPHI] uses mmsystem // background music playing music MCISendString ('Open E: /1.MID TYPE SEQUENCER Alias NN', '', 0, 0); McISendString ('Play Nn from 0', '', 0, 0); McIndString ('Close Animation', '", 0, 0); end; // Stop playing McIndstring ('Open E: /1.MID TYPE SEQUENCER Alias NN', '', 0, 0); McISendString ('Stop NN', ', 0, 0); McISendstring ('close animation ",'
', 0, 0); ◇ [DELPHI] interface and class code type code TYPE {interface and class declaration: difference is that it is not possible to declare data members in the interface, any non-public method, public method does not use public keyword} isample} isample = interface // define Isample Interface function getstring: string; end; Tsample = class (TInterfacedObject, Isample) publicfunction getstring: string; end; // function defined function Tsample.getstring: string; beginresult: = 'what show is'; end ; // call the class object var sample: Tsample; beginsample: = Tsample.create; showmessage (sample.getstring 'class object!'); sample.free; end; // call interface var sampleinterface: Isample; sample: Tsample; beginsample : = Tsample.create; SampleInterface: = Sample; // Interface Implementation must use class {above two lines to reach SAMPLEINTERFACE: = Tsample.create;} showMessage (SampleInterface.getstring 'interface!'); // Sample. Free; {and local classes, type automatic release} sampleInterface: = nil; {Release interface object} end; ◇ [Delphi] task bars will see the program VAREXTendedStyle: Integer; beginApplication.initialize; extendedStyle: = getWindowlong Application.Handle, GWL_EXSTYLE); SetWindowlong (Application.Handle, GWL_EXSTYLE, EXTENDSTYLE OR WS_EX_TOOLWINDOW AND NOT WS_EX_APPWINDOW); Application.createform (TFORM1, FORM1); Application. Run; end ◇ [DELPHI] ALT CTRL DEL see the program adds the statement after the implementation: function RegisterServiceProcess (dwProcessID, dwType: Integer):. Integer; stdcall; external 'KERNEL32.DLL'; RegisterServiceProcess (GetCurrentProcessID, 1) ; // hides RegisterServiceProcess (GetCurrentProcessID, 0); // display ◇ [DELPHI] detecting the drive symbols var drive: char; cdromID: integer; beginfor drive: = 'd' to 'z' dobegincdromID: = GetDriveType (pchar (drive ' : / ')); if CDRomid = 5 Then ShowMessage (' Your CD-ROM: ' Drive ' disk! '); end; end; ◇ [delphi] detection sound card if auxgetnumdevs () <= 0 Then ShowMessage (' NO SoundCard Found! ') Else ShowMessage (' Any SoundCard Found! ');
◇ [Delphi] draws StringGrid.ondrawcell event with stringgrid1.canvas do draw (Rect.graphic); ◇ [SQL Server] SQL instead of another LIKE statement in SQL [SQL Server] SQL If a way to find all users with "c", you can use the USEDATABASE SELECT * from Table1 WHEREEDATAME LIKE '% C% "" Next: Use myDatabase selection * from table1 where charIndex ('c', username)> 0 This method is theory than a judgment statement than the previous method, namely> 0, but this judgment process is the fastest, I want to believe that more than 80% of the operation is spent Find a string and other operations, so it is not very much in use with the charIndex function. It is also beneficial to use this method, that is, you can use it in this CharIndex directly in this char, you can use the characters that you can find directly with Like. : Use mydatabase select * from table1 where charindex ('%', username)> 0 can also be written: Use mydatabase selection * from table1 where charindex (char (37), username)> 0 ASCII characters are% ◇ [Delphi] SQL displays the multi-database / table Select Distinct A.Bianhao, A.XINGMING, B.Gongzi from "jianjie.dbf" a, "gongzi.dbf" b where a.bianhao = B.Bianhao ◇ [Delphi] RFC (Request for Comment ) Related IETF (Internet Engineering Task Force) Maintenance RFC Document http://www.ietf.cnri.reston.va.usrfc882: Packet Signal Structure RFC1521: Mime First Part, Transmission Packet Method RFC1945: Multimedia Document Transfer Document ◇ [Delphi] TNMUUProcessor's use VAR Instream, Outstream: TfileStream; BeginStr eam: = TFileStream.create (infile.txt, fmOpenRead); outStream: = TFileStream (outfile.txt, fmCreate); NMUUE.Method: = uuCode; {UUEncode / Decode} // NMUUE.Method: = uuMIME; {MIME} NMUUE.InputStream: = InStream; NMUUE.OutputStream: = OutStream; NMUUE.Encode; {encoding process} // NMUUE.Decode; {decoding} inStream.free; outStream.free; end; ◇ [DELPHI] TFileStream operation / / From the file stream current location read count bytes into buffer buffunction read (VAR Buffer; count: longride; // read buffer buffer in Function Write (CONST Buffer; Count: longint): LONGINT; OVERRIDE; / / Settings File Current Read Write Pointer for OffsetFunction Seek (Offset: Longint; Origin: Word): longride; Origin =
{SOFROMBEGINNING, SOFROMCURRENT, SOFROMEND} // Current location from another File stream Current location Function CopyFrom (Source: TSTREAM; Count: longint): longint; // Read Specify file to file stream Var myfstream: TFileStream; beginmyFStream: = TFileStream.create (OpenDialog1.filename, fmOpenRead); end; [JavaScript] IE plug can detect the presence Shockwave & Quicktimevar myPlugin = navigator.plugins [ "Shockwave"]; if (myPlugin) document.writeln ( "you have installed Shockwave! ") Elsedocument.writeln (" You have not installed ShockWave! ")
Var myplugin = navigator.plugins ["QuickTime"]; if (MyPlugin) Document.writeln ("You have installed QuickTime!") Elsedocument.writeln ("You have not installed QuickTime!") / End ///