Delphi section skills collection

xiaoxiao2021-03-06  14

Excerpted from http://www.zahui.com/html/2/573.htm

◇ [Delphi] Network neighbor replication file Uses shellapi; copyfile (Pchar ('newfile.txt'), Pchar ('// computername / direction / targer.txt'), false);

◇ [Delphi] Generates the mouse drag effect Through Mousemove event, Dragover event, enddrag event implementation, such as Label: Var XPanel, Ypanel, XLabel, Ylabel: Integer; XPanel: = X; YPANEL: XPANel: = x; Ypanel: = Y; Panel's Dragover event: xPanel: = X; YPANEL: = Y; Label Mousemove event: xlabel: = x; ylabel: = y; label's endDrag event: label.Top: = xpanel-xlabel; label.top : = YPANEL-YLABEL;

◇ [Delphi] gets Windows catalog Uses shellapi; var window, array [0..255] of char; getWindowsDirectory; or read from the registry, location: hkey_local_machine / Software / Microsoft / WINDOWS / CurrentVersionsystemroot key, acquisition, C: / Windows

◇ [delphi] Pipeline VAR X, Y: Array [0..50] of integer; canvas.pen.color: = CLRED; canvash; form1.canvas.moveto (Trunc (x [i]), trunc (y [i])); Form1.canvas.LineTo (Trunc (x [j]), trunc (y [j]));

◇ [Delphi] string list use var tips: tstringlist; tips: = tstringlist.create; tips.loadfromfile ('filename.txt'); edit1.text: = tips [0]; tips.add ('Last Line Additional String '); Tips.insert (1,' INSERT STRING AT NO 2 line '); tips.savetofile (' newfile.txt '); tips.free;

◇ [Delphi] Simple clipboard operates richedit1.selectall; richedit1.copytoclipboard; richedit1.cuttoclipboard; edit1.pastefromclipboard;

◇ [Delphi] About file, directory operation chDIR ('c: / abcdir'); go to the directory MKDIR ('DIRNAME'); establish the directory RMDIR ('DIRNAME'); delete the directory getcurrentdir; // Take the current directory name, no '/' Getdir (0, s); // Take the work directory name s: = 'c: / abcdir'; deleetfile ('abc.txt'); // Delete file renamefile ('ild.txt', 'new. TXT '); // Document Name of ExtractFileName (fileListBox1.FileName); // Take the file name extractFileExt (filename); // Take a file suffix ◇ [Delphi] Process file attribute Attr: = filegetttr (fileListbox1.filename); if (attr and fareadonly) = fareadonly the ... // read-only if (attr and fasysfile) = Fasysfile kil1 ... // System IF (attr and faarchive) = Faarchive the ... // Archive IF (Attr and Fahidden ) = fahidden kil ... // Hide

◇ [Delphi] Execute the program external file WINEXEC // Call the executable Winexec ('command.com / c copy *. * C: /', sw_normal); Winexec ('start abc.txt'); shellexecute or shellexecuteEx // Start file associated program Function Executefile (const filename, params, defaultdir: string; showcmd: integer): thandle; executefile ('c: /abc/a.txt', 'x.abc', 'C: / ABC /', 0); Executefile ('http: //tingweb.yeah.net' ,'' ,'',0); Executefile (' Mailto: Tingweb@wx88.net ',' ',', 0);

◇ [DELPHI] acquiring system running process name var hCurrentWindow: HWnd; szText: array [0..254] of char; beginhCurrentWindow: = Getwindow (handle, GW_HWndFrist); while hCurrentWindow <> 0 dobeginif Getwindowtext (hcurrnetwindow, @ sztext, 255)> 0 Then ListBox1.items.add (@sztext)); hcurrentWindow: = getWindow (HcurrentWindow, GW_HWndNext); end;

◇ [Delphi] embedded ASM end in assembly; can modify Eax, ECX, EDX can be arbitrarily modified; ESI, EDI, ESP, EBP, EBX can not be modified.

◇ [Delphi] About Type Conversion Function FLOATTOSTR / / Floating Stroke FloatTostrf // Floating Stroke InttoHex // Integer Transfer 16 Enter TimetostrDateTrDateTiMetostrfMTSTRDATSTRDATSTRFMTSTRDATSTRDATSTRDTSTRDATSTRFMTSTR / / Output String FormatDateTime ('YYYY-MM) -DD, HH-MM-SS ', DATE

◇ [DELPHI] string process and function insert (OBJ, Target, POS); // String Target is inserted in POS. If the insertion result is greater than the maximum length of Target, multiple characters will be cut off. Such as POS is 255, it will generate an error. For example, st: = 'brian', INSERT ('OK', ST, 2) will make ST to 'Brokian'. Delete (ST, POS, NUM); // From the POS (integer) position in the ST string, the number of substrings of NUM (integer) characters are started. For example, st: = 'brian', the delete (ST, 3, 2) will become BRN. Str (Value, ST); // Convert value value (integer or real) into a string in ST. For example, when A = 2.5E4, the STR (A: 10, ST) will make the value of the ST '25000'. VAL (ST, VAR, CODE); // converts string expressions to a corresponding integer or real value, stored in VAR. St must be a string representing a value and complies with the rules of the numerical constant. During the conversion process, if an error is not detected, the variable code is set to 0, otherwise it is positioned as the first error character. For example, st: = 25.4e3, X is a real variable, the VAL (ST, X, CODE) will make the X value of 25400, the Code value is 0. Copy (st.pos.num); // Returns a substring containing Num (integer) characters at a position POS (integer) in the ST string. If the POS is greater than the length of the ST string, it will return an empty string. If POS is outside 255, it will cause an error. For example, st: = 'brian', then COPY (ST, 2, 2) returns 'ri'. Concat (ST1, ST2, ST3 ..., STN); // Connect all the strings indicated by all the variables, and returns the connected value. If the length 255 of the result will generate an operation error. For example, St1: = 'brian', ST2: = '', ST3: = 'WILFRED', then CONCAT (ST1, ST2, ST3) returns 'Brian Wilfred'. Length (ST); // Returns the length of the string expression ST. For example, St: = 'brian', the longth (ST) returns 5. POS (OBJ, TARGET); // Returns the first appearance of the string OBJ at the target string Target, if the target does not match the string, the return value of the POS function is 0. For example, Target: = 'Brian Wilfred', the return value of POS ('WIL', TARGET) is 7, and the return value of POS ('Hubet', Target) is 0.

◇ [Delphi] About Processing Registry Uses Registry; Var REG: Tregistry; Reg: = Tregistry.create; REG.ROOTKEY: = 'HKEY_CURRENT_USER'; Reg.OpenKey ('Control Panel / Desktop', false); reg.writestring 'Title Wallpaper', '0'); reg.writeString ( 'Wallpaper', filelistbox1.filename); reg.closereg; reg.free; ◇ [DELPHI] on the keyboard constant name VK_BACK / VK_TAB / VK_RETURN / VK_SHIFT / VK_CONTROL / VK_MENU / VK_PAUSE / VK_ESCAPE / VK_SPACE / VK_EFT / VK_RIGHT / VK_UP / VK_DOWNF1 - F12: $ 70 (112) - $ 7B (123) AZ: $ 41 (65) - $ 5A (90) 0-9: $ 30 (48) $ 39 (57) ◇ [Delphi] Preliminary judgment program Native Delphi software DOS Tips: This Program Must Be Run Under Win32.VC software DOS Tips: This Program Cannot Be Run in Dos Mode.

◇ [Delphi] Operation Cookieresponse.cookies ("name") .Domain: = 'http://www.086net.com'; with response.cookies.add dobeginname: = 'username'; value: = 'username'; end

◇ [Delphi] Added to the document menu connection Uses shellapi, shlobj; shaddtorecentdocs (Shard_Path, Pchar (filepath)); // Added ShaddtorecentDocs (Shard_Path, NIL); // Clear

◇ [Miscellaneous] Backup Intelligent ABC Input French Word Library Windows / System / User.RemWindows / System / Tmmr.Rem

◇ [Delphi] Judgment Mouse Buttons If getasyncKeyState (vk_lbutton) <> 0 THEN ... // Left button if getasynckeystate (vk_mbutton) <> 0 Then ... // 中键 f GetasyncKeyState (vk_rbutton) <> 0 THEN .. . // Right button

◇ [Delphi] Set the maximum display of the form ONFORMCREATE Event Self.Width: = Screen.Width; Self.height: = Screen.Height;

◇ [Delphi] button accepts the message oncreate event: Application.onMessage: = MyonMessage; Procedure TFORM1.MYONMESSAGE (VAR MSG: TMSG; var Handle: Boolean); beginif msg.MESSAGE = 256 Then ... // ANY key IF Msg.Message = 112 Then ... // f1if msg.Message = 113 THEN ... / / F2END;

◇ [Miscellaneous] Hide Shared Folder Sharing Effect: Access, but invisible (in resource management, network neighbors) Take a shared name: Direction $ Access: // Computer / Dirction /

◇ [Java Script] Java Script webpage common effects page 60 seconds timing close

Close window Close Time to turn the URL Set as Homepage to Home Favorite This site Add to Channel Add to Channel

◇ [Delphi] randomly generates text color randomize; // Random seed memo1.font.color: = RGB (Random (255), Random (255));

◇ [delphi] Delphi5 Update upgrade patch sequence number 100000318590x25fx0

◇ [Delphi] file name illegal character filtering for i: = 1 to length (s) doif s [i] in ['/', '/', ':', '*', '?', '<' , '>', '|'] THEN

◇ [DELPHI] Conversion Function and Description DateTimeTOFILEDATE: Longint String, if the datetime parameter does not include the date value, the return string date is displayed to be 00/00/00, if there is no time value in the datetime parameter, the time part of the return string is displayed to 00:00:00 AmdateTimetostring (Var Result String; Const format: string; datetime: tdatetime); Result is the result string, format is the resulting time value DateTostr (date: tdatetime) using shortette: tdatetime for the conversion format string, Datetime is a SHORTDATEFORMAT The format string defined by the variable converts the DATE parameter into a corresponding string floattodecimal (var Result: TfloatRec; value: integer; converted); convert the floating point number into a decimal representation FLOATTOSTR (value: extended): String will float Point value is converted into a string format, which uses a normal digital format, and the number of effective bits of the conversion is 15 bits. FLOATTETEXT (Buffer: Pchar; Value: Extended; Format: Tfloatformat; Precision, Digits: Integer: Integer; Convert the floating point value value VALUE into a decimal representation with a given format, accuracy and decimal, and the conversion results are stored in the buffer parameter The function return value is the number of characters stored in the buffer, and buffer is a string buffer with non-zero results. FLOATTETEXTFMT (Buffer: Pchar; Value: Extended; Format: Pchar): Integer Converts floating point value value VALUE into a decimal form in a given format, the conversion result is stored in the buffer parameter, the function returns the value stored in the buffer. Bit number. INTTOHEX (value: long): string; converts a given value value value into hexadecimal strings. Parameter DIGITS gives the number of digits contained in the conversion result string. INTOSTR (Value: longint): String converts an integer into a decimal form string strandate (const S: String): TDATETIME converts a string into a date value, and s must contain a list of legitimate formatted dates. STRTODATETIME (const S: string): TDATETIME converts string S to date time format, s must have mm / dd / yy hh: mm: SS [AM | PM] format, where date and time separator and system time constant Set. If the AM or PM information is not specified, it means 24 hours.

STRTOFLOAT (Const S: String): Extended; converts a given string into floating point numbers, strings have the following format: [ | -] nnn ... [.] nnn ... [< | -> < | -> NNNN] STRTOINT (const S: String): Longint converts the numeric string into an integer, the string can be a decimal or hexadecimal format, if the string is not a legitimate digital string, the system occurs EconvertError Abnormally STRTOINTDEF (Const S) : string; default: longint: longint; converts string S into numbers, if S is not converted into numbers, the STRTOINTDEF function returns the value of parameter default. Strtotime (const s: string): TDATTIME converts strings S to TDATETIME values, S has HH: MM: Ss [AM | PM] format, the actual format is related to the overall variable related to the system time. Timetostr (Time: TDATETIME): String; convert the parameter time into a string. The format of the conversion result string is related to the setting of the time-related constant of the system. ◇ [DELPHI] procedure does not appear to add ALT CTRL DEL statement after implementation: function RegisterServiceProcess (dwProcessID, dwType: Integer): Integer; stdcall; external 'KERNEL32.DLL'; RegisterServiceProcess (GetCurrentProcessID, 1); // Hide RegisterServiceProcess (getcurrentprocessid, 0); // Show Alt Del Ctrl invisible

◇ [Delphi] program does not appear in the taskbar Uses WindowsvarextendedStyle: Integer; beginApplication.initialize; / / ============================= =============================================== = getWindowlong (Application.Handle, GWL_EXSTYLE); setWindowlong (Application.Handle , GWL_EXSTYLE, EXTENDEDSTYLE OR WS_EX_TOOLWINDOWAND NOT WS_EX_APPWINDOW); / / ======================================= ================================== Application.createform (TFORM1, FORM1); Application.Run; end. ◇ [DELPHI] How to determine the dial-up network is open Still IF GetSystemMetrics (SM_Network) and $ 01 = $ 01 THENSHOWMESAGE ('Online!') Else ShowMessage ('Not online!');

◇ [Delphi] Implementing the conversion of IP to domain name (IP: string): string; varPh: phostent; data: twsadata; ii: dWord; Beginwsastartup ($ 101, data); ii: = inet_addr (PCHAR (IP)); PH: = gethostbyaddr (@ ii, sizeof (ii), pf_inet); if (pH <> nil) ThenResult: = ph.h_nameelseresult: = '; WSACLANUP; END;

◇ [Delphi] Handle "Right-click Menu" method varreg: Tregistry; beginreg: = Tregistry: = hkey_classes_rootkey: = hkey_classes_rootkey; reg.openkey ('* / shell / check / command', true); reg.writestring (' ',' "" ' application.exename "% 1"); reg.closekey; reg.openkey (' * / shell / diary ', false); reg.writeString (' ',' operation (& c) '); reg.CloseKey; reg.Free; showmessage (' DONE ');! end; ◇ [DELPHI] sending a virtual key ctrl Vprocedure sendpaste; beginkeybd_event (VK_Control, MapVirtualKey (VK_Control, 0), 0, 0); keybd_event (ORD ('V'), MapVirtualKey (ORD ('V'), 0), 0, 0); KeyBD_Event (ORD ('V'), MapVirtualKey (ORD ('V'), 0), KeyEventf_Keyup, 0) KeyBD_EVENT (VK_Control, MapVirtualKey (VK_Control, 0), KeyEventf_Keyup, 0);

◇ [Delphi] Current Copular Drive Procedure Getcdrom (VAR CD: Char); Varstr: String; Drivers: Integer; Driver: Char; I, TEMP: Integer; Begindrivers: = getLogicalDrives; Temp: = (1 and Drivers) For i: = 0 to 26 dobeginif Temp = 1 Thenbegindriver: = CHAR (i integer ('a')); str: = driver ':'; if getDriveType (PCHAR (STR)) = Drive_cdrom damEgIncd: = driver; EXIT; END; end; drivers: = (Drivers SHR 1); TEMP: = (1 and drivers); end; end;

◇ [Delphi] Character encryption and decryption Function Cryptstr (const S: string; style: string; vari: integer; fkey: integer; beginResult: = '; case stype in0: setPass; beginrandomize; fkey: = random ($ ff); for i: = 1 to length (s) doresult: = Result chr (ORD (S [i]) xor i xor fkey); Result: = Result char (fkey); end; 1: getPassBeginfkey : = ORD (S [LENGTH (S)]); for i: = 1 to Length (s) - 1 doreSult: = Result CHR (ORD (S [i]) xor i xor fkey); end; end;

□ □ [Delphi] Send analog key to other applications VARH: Thandle; Beginh: = FindWindow (NIL, 'application title "; PostMessage (h, wm_keydown, vk_f9, 0); // Send F9 key END; □ ◇ [Delphi] DELPHI supported DAO data format Td.fields.Append (TD.CREATEFIELD (TD.CREATEFIEAN, 0)); TD.Fields.Append (TD.CREATEFIELD ('dbbyte', dbbyte, 0); TD .Fields.Append ('dbinteger', dbinteger, 0)); Td.fields.Append (Td.createField ('dblong', dblong, 0)); td.fields.Append (TD.CREATEFIELD (' Dbcurrency ', dbcurrency, 0); TD.Fields.Append (TD.CREATEFIELD (' dbsingle ', dbsingle, 0)); TD.Fields.Append (TD.CREATEFIELD (' DBDOUBLE ', DBDOUBLE, 0); TD .Fields.append (TD.CREATEFIELD ('DBDATE', DBDATE, 0); Td.fields.Append (Td.createField ('dbbonary', dbinary, 0)); TD.Fields.Append (TD.CREATEFIELD (' DBText ', dbtext, 0); TD.Fields.Append (' dblongbinary ', dblongbinary, 0)); td.fields.Append (TD.CREATEFIELD (' dbmemo ', dbmemo, 0)); TD .Fields ['id']. Set_attributes (dbautoincrfield); // Self-adding field

□ □ [Delphi] Delphi Configuration MS SQL 7 and BDE Steps First Step, Configure ODBC: Set the data source in ODBC, after installing SQL Server 7.0, there is a "system DSN" in ODBC should have two data sources. One is MQIS, one is localsever, optionally a selected click configuration button, I don't know if your SQL7.0 is installed on the local machine, if not, let's go directly, if not, fill in the server column Server, then proceed, fill in the login ID and password (the login ID, and password are set in the user options in SQL7.0). Step 2, configure BDE: Open Delphi BDE, then click MQIS or LocalServer, you will prompt the username and password, which is the same as the ODBC username and password, fill it. Step 3, the configuration program: If you use a TTable, select MQIS or LocalServer in the TTable DatabaseName, then select Sale in TableName, then change the Active to True, Delphi pops up the prompt dialog, fill in the username and password . If you use tQuery, click the right button on TQuery, then strike "SQL Builder", which is configured in the interface to configure the SQL statement, or fill in the SQL statement in the TQUERY SQL. Finally, don't forget to change Active to True. It is also possible to configure TQuery, see Delphi Help. □ □ [delphi] Gets a point of the image on a point of the RGB value TFORM1.IMAGE1MOUSEDOWN (Sender: Tobject; Button: TMouseButton; Shift: TshiftState; x, y: integer; varred, green, blue: byte; i: integer; begini = Image1.canvas.pixels [x, y]; blue: = getBValue (i); green: = getgvalue (i): red: = getRvalue (i); label1.caption: = INTOSTR (red); label2.caption : = INTOSTR (Green); label3.caption: = INTOSTR (blue);

□ □ [Delphi] About Date Format Decomposition Translation VAR Year, Month, Day: Word; Now2: TDataTime; NOW2: = DATE (); DECODEDATE (NOW2, YEAR, MONTH, DAY); LABLE1.TEXT: = INTOSTR (YEAR) 'Year' INTOSTR (MONTH) 'Moon' INTOSTR (DAY) 'Day'

◇ [DELPHI] How to determine the current network connection method is the MODEM, a local area network, or a proxy server mode. uses wininet; Function ConnectionKind: boolean; var flags: dword; beginResult: = InternetGetConnectedState (@flags, 0); if Result thenbeginif (flags and INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM thenbeginshowmessage ( 'Modem'); end; if (flags and INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN thenbeginshowmessage ( 'LAN'); end; if (flags and INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY thenbeginshowmessage ( 'Proxy'); end; if (flags and INTERNET_CONNECTION_MODEM_BUSY) = INTERNET_CONNECTION_MODEM_BUSY thenbeginshowmessage ( 'Modem Busy'); end; end; end; ◇ [Delphi] How to determine if the string is a valid email address Function ISEMAIL (email: string): boolean; var s: string; etc = POS: Integer; becomes: = POS ('@', email); if etc @ @ @ ', email); if etc COPY (Email, ETPOS 1, Length); IF (POS ('.', s)> 1) AND (POS ('.', s)

◇ [DELPHI] Judging whether the system is connected to the Internet to introduce the inetisoffline function in the Url.dll. Function is declared as: function InetIsOffline (Flag: Integer): Boolean; stdcall; external 'URL.DLL'; then can call the function determines whether the system is connected to INTERNETif InetIsOffline (0) then ShowMessage else ShowMessage (( 'not connected!') 'Connected!'); This function returns true if the local system is not connected to the Internet. Attachment: Most systems with IE or Office97 have this DLL for call. InetisofflineBool inetisoffline (DWORD dwflags);

◇ [Delphi] Simply play and suspend WAV files Uses MMSystem;

Function Playwav (const filename: string): Boolean; BeginResult: = Plays (pchar (filename), 0, SND_ASYNC); END;

Procedure stopwav; varbuffer: array [0..2] of char; becombuffler [0]: = # 0; Playsound (buffer, 0, snd_purge);

◇ [Delphi] Take the machine BIOS information with memo1.lines dobleginadd ('mainboardbiosname:' ^ i string (Ptring (Ptr (PTR ($ FE061))))); add ('mainboardbioscopyright:' ^ i string (PCHAR (Ptring ($ FE091))))))))); add ('mainboardbiosdate:' ^ i string (PCHAR (PTR ($ fff5))))))); add ('mainboardbiosserialno:' ^ I string (PCHAR (Ptr (PTR ($ fec71) ))))); END; ◇ [Delphi] network download file Urlmon;

Function Downloadfile (Source, Dest: String): Boolean; BeginTryResult: = URLDOWNLOADTOFILT: = URLDOWNLOADTOFILE (NIL, PCHAR (SOURCE), PCHAR (DEST), 0, NIL) = 0; EXCEPTRESULT: = FALSE; END;

If Downloadfile ('http://www.borland.com/delphi6.zip,' c: / kylix.zip ') ThenshowMessage (' Download unsuccesful ') Else ShowMessage

◇ [Delphi] parsing server IP address Uses Winsock

function IPAddrToName (IPAddr: String): String; varSockAddrIn: TSockAddrIn; HostEnt: PHostEnt; WSAData: TWSAData; beginWSAStartup ($ 101, WSAData); SockAddrIn.sin_addr.s_addr: = inet_addr (PChar (IPAddr)); HostEnt: = gethostbyaddr (@ Sockaddrin.sin_addr.s_addr, 4, af_inet); if Hostent <> nil dam = strpas (hostent ^ .h_name) else result: = ''; end;

◇ [DELPHI] acquired connection function ExeFromLink (const linkname: string): in the shortcut string; varFDir, FName, ExeName: PChar; z: integer; beginExeName: = StrAlloc (MAX_PATH); FName: = StrAlloc (MAX_PATH); FDir : = StrAlloc (MAX_PATH); StrPCopy (FName, ExtractFileName (linkname)); StrPCopy (fDir, ExtractFilePath (linkname)); z: = FindExecutable (FName, fDir, ExeName); if z> 32 thenResult: = StrPas (ExeName) Elseresult: = '; strdispose (fdir); strdispose (fname); strdispose (Exename);

◇ [DELPHI] automatically controlling the TComboBox { 'Sorted' property of the TCombobox to true} var lastKey: Word; // // TCombobox the global variable OnChange event procedure Tform1.AutoCompleteChange (Sender: TObject); varSearchStr: string; retVal : integer; beginSearchStr: = (Sender as TCombobox) .Text; if lastKey <> VK_BACK then // backspace: VK_BACK or $ 08beginretVal: = (Sender as TCombobox) .Perform (CB_FINDSTRING, -1, LongInt (PChar (searchStr)) ); if retval> CB_ERR THENBEGIN (Sender as TcomboBox) .itemindex: = RetVal; (Selstart: = Length (SearchStr); (Sender As TCOMBOBOX) .sellength: = (Length (Sender AS TcomboboX). Text) - Length (searchStr)); end; // retVal> CB_Errend; // lastKey <> VK_BACKlastKey: = 0; // reset lastKeyend; // onKeyDown event TCombobox the procedure Tform1.AutoCompleteKeyDown (Sender: TObject; var Key: Word; Shift: TShiftState); beginlastKey: = Key; end; ◇ [DELPHI] how to empty a directory function EmptyDirectory (TheDirectory: String; Recursive: Boolean): Boolean; varSearchRec: TSearchRec; Res: Integer; beginResult: = False; TheDirectory : = Normaldir; res: = findfirst (TwiRectory '*. *', Faanyfile, searchrec); trywhile res = 0 dobeginif (searchRec.name <> '.') And (searchrec.name <> '..') thenbeginif ((SearchRec.Attr and faDirectory)> 0) and Recursivethen beginEmptyDirectory (TheDirectory SearchRec.Name, True); RemoveDirectory (PChar (TheDirectory SearchRec.Name)); endelse beginDeleteFile (PChar (TheDirectory SearchRec.Name)) end End; res: = findnext (searchRec); end; result: = true; finallyfindclose (searchRec.FindHandle); end;

◇ [DELPHI] installer How to add to the Uninstall list operation registry, as follows: 1. Create a primary key under the hkey_local_machine / currentversion / uninstall key, which 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}

Procedure TFORM1.WMQUERYENDSESSION (VAR Message: TwmqueryEndSession); BeginshowMessage ('Computer Is About To Shut Down ";

◇ [Delphi] Get online neighbors procedure getnethood (); // NT makes the server, and Win98 debug passes.

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;

◇ [delphi] gets hard disk serial number VAR Serialnum: pdword; A, B: DWORD; BUFFER: Array [0..255] of char; beginif getVolumeInformation ('c: /', buffer, sizeof (buffer), serialnum, A , B, NIL, 0) THEN Label1.caption: = INTOSTR (Serialnum ^); End; 1. About MDI Main Factory Background New Solution Add Image Control Add Image Control to IMG_BK in the Create Event of Foem Write self.brush.bitmap: = IMG_BK.PICTURE.BITMAP;

2. Painting the VCL control at the title bar (a line to solve the problem !!!) In the ONPAINT event in Form.PointTo (GETDC (0), Left, TOP);

3 EDIT inputs only setwindowlong (edwindowl "or es_number); 4. Similar to MDI mode new solutions to set Child's oncreate mode: Self.Parent: = ' To set to Mainform's Form ';

5. Refresh (only one line!) RedRawwindow (0, nil, 0, rdw_eredw_allchildren); | | - ---------------------------------------------------- The Windows Directive of the Directive! PaintDesktop (GetDC (0));

7. Extended control new features In programming, we often control the action of the control, but the control does not provide this method.

At this time, you can give this control by sending a message to achieve our goal!

Such as: Button1.Perform (WM_KeyDown, 13, 0);

ListBox1.Perform (WM_VScroll, SB_LINEDOWN, 0);

Wait for you to overload !!!!!

8. Flashing titles such as printer timeout (one line) Form put a Timer control

Write in the TIME event;

FlashWindow (Application.handle, True);

9. Add a VCL control on the desktop! (Not painted, not refresh) Windows.SetParent (control .handle, 0);

Note: I want to put it, such as 'start status bar')

10. About the 'similar MDI mode new solution (one line !!!!)' 'corrected Windows.SetParent (Self.handle,' to set to Mainform's Form ');

11 Ordinary FORM IX MDI MDI is always at the bottom setActiveWindow (0); or setwindowpos (...); 12 Perform the following statement to start the Windows screen saver sendMessage (hwnd_broadcast, wm_sysCommand, sc_screensave, 0); 13 Button's CAPTION Multi-line Display: setWindowlong (Button1.Handle, GWL_Style, getWindowl (Button1.handle, GWL_Style) or bs_multiline); if necessary, add Button1.inValidate;

14. Whole death windows98 :) ASM INT $ 19 Endq: How to change the font of ListBox? Modify one of the rows.

A: Set the listbox1.style to lbownerdrawfixed and write as follows under the OnDrawItem event.

procedure TForm1.ListBox1DrawItem (Control: TWinControl; Index: Integer; Rect: TRect; State: TOwnerDrawState); var Offset: Integer; begin Offset: = 2; with (Control as TListBox) .Canvas do begin FillRect (Rect); if Index = 2 Then Begin font.name: = 'fixedsys'; font.color: = CLRED; font.size: = 12; end else begin font.name: = 'arial'; font.color: = CLBLACK; font.size: = 8; End; if ify; = clwhite; end; textout (Rect.LEFT Offset, Rect.top, (Control as TListBox) .Ind; end;

Q: How to insert a picture in richedit?

A: Please come here to see if you will find the answer.

http://www.undu.com/articles/991107c.html

Q: How can I get the directory?

A: I am coming.

Uses shellapi;

Procedure deletefiles (Source: string); Var fo: tshfileopstruct; Begin Fillchar (fo, sizeof (fo), # 0); fo.wnd: = form1.handle; fo.wfunc: = fo_delete; fo.pfrom: = pchar Source); SHFILEOPERATION (FO); END;

Procedure EmptyDirectory (path: string); Begin if Directoryexists (path) THEN BEGIN Deletefiles; Else Forcedirectories (PATH); END;

Q: How to map the network drive?

For example, I want to map File: // Server / Sys to F. I need a function such as

Give an input parameter for file: // server / sys / home / bruno to me the return value is f: / home / bruno

A:

Function UNCToDrive (UNCPath: STring): STring; var DriveNum: Integer; DriveChar: Char; DriveBits: set of 0..25; StartSTr, TestStr: STring; begin result: = UNCPath; StartSTr: = UNCPath; Integer (DriveBits): = GetLogicalDrives; for DriveNum: = 0 to 25 do begin if (DriveNum in DriveBits) then begin DriveChar: = Char (DriveNum Ord ( 'A')); TestSTr: = ExpandUNCFileName (DriveChar ': /'); If TEstStr < > '' THEN IF POS (Uppercase (Teststr), Uppercase (StartStr))> 0 The Begin Delete (StartStr, 1, Length; Result: = Drivechar ': /' StartStr; Break; End; End; end; q: I have some special language fonts, they are stored in my exe file, but two points.

* I don't want to put it in the font folder * I don't want to extract from the exe file.

If possible, please tell me.

Because my font is not what I do, I want to protect my own things.

A: It is unlikely to be extracted. You can use this protection process to protect your files that are not modified and deleted.

Place the font in the temporary folder when Exe is executed, and delete it at the end.

function ProtectFile (sFilename: string): hFile; var hf: hFile; lwHFileSize, lwFilesize: longword; ofs: TOFStruct; begin if FileExists (sFilename) then begin hf: = OpenFile (pchar (sFilename), ofs, OF_READ or OF_WRITE or OF_SHARE_EXCLUSIVE ); If hf <> 0 THEN becom lwfilesize: = getFileSize (hf, @Lwhfilesize); if lockfile (HF, 0, 0, LWFILESIZE, LWHFILESIZE) THEN RESULT: = HF else result: = 0; Else Result: = 0 END ELSE RESULT: = 0;

//..var ResS: TResourceStream; TempPath: array [0..MAX_PATH] of Char; TempDir: string; begin GetTempPath (Sizeof (TempPath), TempPath); TempDir: = StrPas (Path); ResS: = TResourceStream.Create (hInstance, 'SOME_FONT', 'RT_FONT'); ResS.SavetoFile (TempDir 'some_font.ttf'); ResS.Free; AddFontResource (TempDir 'some_font.ttf'); SendMessage (HWND_BROADCAST, WM_FONTCHANGE, 0, 0); ProtectFile (Tempdir 'Some_Font.ttf'); End; Q: How to get the current ProgramFiles to get the path?

A: You can do it with the method of reading and writing.

code show as below:

Uses registry;

procedure TForm1.Button1Click (Sender: TObject); var reg: TRegistry; begin reg: = TRegistry.Create; reg.RootKey: = HKEY_LOCAL_MACHINE; if reg.OpenKey ( 'SOFTWARE / Microsoft / Windows / CurrentVersion', false) then begin edit1 .Text: = reg.readstring ('programfilesdir'); reg.closekey; reg.free; end; end;

Q: How do I write on the JPG image?

A: There is a code here.

HMM, Here's A Sample with help of bitmap, you can chance the brush style of canvas to bsclear to make the text transparent

Uses JPEG;

procedure TForm1.Button1Click (Sender: TObject); var Bmp: TBitmap; Jpg: TJpegImage; begin try Bmp: = TBitmap.Create; Jpg: = TjpegImage.Create; Jpg.LoadFromFile ( 'c: /img.jpg'); Bmp .Ssign (jpg); bmp.canvas.brush.style: = bsclear; bmp.canvas.font.color: = ClyEllow; bmp.canvas.textout (10, 10, 'hello world "; jpg.assign (BMP) Jpg.savetofile ('c: /img2.jpg'); finally bmp.free; jpg.free; end; end;

Q: How to use Delphi to modify the file time?

Under Windows, there are three days, create, modify, and store in the properties. How can I change it?

A: Here is The Excerpt from The Jedi Code Library. If IT IS Not Complete Then Get The JCL.

type // indicates the file time to set, used by SetFileTimesHelper and SetDirTimesHelper TFileTimes = (ftLastAccess, ftLastWrite, ftCreation); function SetFileTimesHelper (const FileName: string; const DateTime: TDateTime; Times: TFileTimes): Boolean; var Handle: THandle; FileTime: TFileTime; SystemTime: TSystemTime; begin Result: = False; Handle: = CreateFile (PChar (FileName), GENERIC_WRITE, FILE_SHARE_READ, nil, OPEN_EXISTING, 0, 0); if Handle <> INVALID_HANDLE_VALUE then try //SysUtils.DateTimeToSystemTime ( DateTimeToLocalDateTime (DateTime), SystemTime); SysUtils.DateTimeToSystemTime (DateTime, SystemTime); if Windows.SystemTimeToFileTime (SystemTime, FileTime) then begin case Times of ftLastAccess: Result: = SetFileTime (Handle, nil, @FileTime, nil); ftLastWrite: Result: = setFiletime (Handle, NIL, NIL, @filetime); FTCREATION: Result: = setFileTime (Handle, @filetime, nil, nil); end; end; finally closehandle (handle); end;

/ / -------------------------------------------------------------------------------------------- --------------------------------------------------

Function setFileLastAccess (const datetime: tdatetime): boolean; begin result: = setFileTimesHelper (filename, datetime, ftlastaccess);

/ / -------------------------------------------------------------------------------------------- --------------------------------------------------

Function setFileLastWrite (const datetime: tdatetime): boolean; begin result: = setFileTimeShelper (filename, datetime, ftlastwrite);

/ / -------------------------------------------------------------------------------------------- --------------------------------------------------

Function setFilecreation (const datetime: tdatetime): boolean; begin result: = setFileTimeShelper (filename, datetime, ftcreation); end; Google About Delphi's website:

http://directory.google.com/top/computers/programming/languages/delphi/?tc=1

On Yahoo about Delphi URL

Http://dir.yahoo.com/computers_and_internet/programming_and_development/languages/delphi/

Delete the program's own EXE file procedure tform1.formclose (Sender: Tobject; var action: tclosection); var f: textfile; begin assignfile; begin associle (f, 'delself.bat'); REWRITE (f); {f is textFile type} Writeln (f, 'del' extractFilename (Application.exename); WriteLn (f, 'del% 0'); // Delete Delself.Bat Closefile (f); Winexec ('delself.bat', sw_hide); END;

IF ORD (S [9])> 128 Then ShowMessage ('This position character is Chinese characters'); Chinese characters are double-bytes of change system time format:

Var str: string; begin str: = 'yyyy-mm-dd'; if setLocaleInfaua (locale_system_default, local_slongdate, pchar (str)) The begin showMessage ('Change Date Format Success'); End; End;

Take a break: VARI: Integer; Begin i: = gettickcount; while (gettickcount-i) <= 10000 do application.processMessages; // guarantee message loop END;

Take the host file name: Function retufilename (const filename: string): string; var i: integer; begin i: = lastdelimiter ('.', Filename); Result: = Copy (FileName, 1, I-1);

END;

(1). A event after the Ctrl and other keys are pressed. Procedure TFORM1.FORMKEYDOWN (Sender: Tobject; var key: word; shift: tshiftstate); begin if (ssctrl in shift) and (key = 67) Then ShowMessage ('KeyDown Ctrl C'); END; (2) .dbgrid Tab key instead of the Enter key using procedure TForm1.DBGrid1KeyPress (Sender: TObject; var key: Char);. begin if key = # 13 then if ActiveControl = DBGrid1 then begin TDBGrid (ActiveControl) .SelectedIndex: = TDBGrid (ActiveControl) .SelectedIndex 1; Key: = # 0; end; end; (3). Select Multi-line events in. DBGRID. procedure TForm1.Button1Click (Sender: TObject); var i: integer; bookmarklist: Tbookmarklist; bookmark: tbookmarkstr; begin bookmark: = adoquery1.Bookmark; bookmarklist: = dbgrid1.SelectedRows; try begin for i: = 0 to bookmarklist.Count- 1 do begin adoquery1.Bookmark: = bookmarklist [i]; with adoquery1 do begin edit; fieldbyname ( 'mdg') AsString:. = edit2.Text; post; end; end; end; finally adoquery1.Bookmark: = bookmark; end End; (4). A appearance effect of form. Procedure TForm1.Button1Click (Sender: TOBJECT); VAR R: THANDLE; I: Integer; Begin for i: = 1 to trunc (width / 1.414) Do Begin R: = CreatellipticRgn (Trunc (Width / 2) -i, Trunc ( Height / 2) -i, trunc (width / 2) i, trunc (height / 2) i); setWindowRgn (Handle, R, True); Application.ProcessMessages; Sleep (1); End; End; (5) . Use Enter instead of TAB to move in the edit box.

procedure TForm1.FormKeyPress (Sender: TObject; var Key: Char); begin if key = # 13 then begin if not (Activecontrol is Tmemo) then begin key: = # 0; keybd_event (vk_tab, mapvirtualkey (vk_tab, 0), 0 , 0); end; end; end; (6) .progressbar plus color. const {$ EXTERNALSYM PBS_MARQUEE} PBS_MARQUEE = 08; var Form1: TForm1; implementation {$ R * .dfm} uses CommCtrl; procedure TForm1.Button1Click (Sender: TObject); begin // Set the Background color to teal Progressbar1.Brush.Color : = CLTEAL; // SET Bar Color To Yellow SendMessage (ProgressBar1.Handle, PBM_SetBarcolor, 0, ClyEllow); END; (7). Edit box color when the point is moving.

Procedure tform1.edit1enter (sender: TOBJECT); Begin (Sender as tedit) .COLOR: = CLRED; end; procedure tform1.edit1exit (sender: TObject); recomcolor: = CLWHITE; END; (8) ) backup and recovery procedure TForm1.Button1Click (Sender:. TObject); begin if OpenDialog1.Execute then begin try adoconnection1.Connected: = False; adoconnection1.ConnectionString: = 'Provider = SQLOLEDB.1; Persist Security Info = False; User ID = sa; Initial Catalog = master; Data Source = FRIEND-YOFZKSCO; ' ' Use Procedure for Prepare = 1; Auto Translate = True; Packet Size = 4096; Workstation ID = FRIEND-YOFZKSCO; Use Encryption for Data = False; Tag with column collation when possible = False '; adoconnection1.Connected: = True; with adoQuery1 do begin Close; SQL.Clear; SQL.Add (' Backup DataBase sfa to disk = '' ' opendialog1.FileName ' '' '); Exceql; End; Except ShowMessage ('±? · Yê§ ° ü'); EXIT; END; End; Application.MessageBox ('1 §? 2? Ú? Êy? Y ±? · Y3é1 |', 'ìáê?', MB_OK MB_ICONITIONFORMATION; End; ProCedure TFORM1.BUTTON2CLICK (Sender: TOBJECT) ; begin if OpenDialog1.Execute then begin try adoconnection1.Connected: = false; adoconnection1.ConnectionString: = 'Provider = SQLOLEDB.1; Persist Security Info = False; User ID = sa; Initial Catalog = master; Data Source = FRIEND-YOFZKSCO ; ' ' Use procedure for prepare = 1; auto translate = true; packet size = 4096;

转载请注明原文地址:https://www.9cbs.com/read-46140.html

New Post(0)