DEPHI SKILLS 1

xiaoxiao2021-03-06  40

Delphi classic skills

Q: How to make DEL CTRL ALT can't see the program operation? A: In order to make the program use Alt Del Ctrl, add declaration after IMPLEMentation: Function RegisterServiceProcess (dwprocessid, dwtype: integer): integer; stdcall; external ' KERNEL32.DLL '; then add a window above Create event: RegisterServiceProcess (GetCurrentProcessID, 1); // hides may also use the following function: function My_SelfHide: Boolean; typeTRegisterServiceProcess = function (dwProcessID, dwType: DWord): DWORD ; stdcall; varhNdl: THandle; RegisterServiceProcess: TRegisterServiceProcess; beginResult: = False; if Win32Platform <> VER_PLATFORM_WIN32_NT then // not NTbeginhNdl: = LoadLibrary ( 'KERNEL32.DLL'); RegisterServiceProcess: = GetProcAddress (hNdl, 'RegisterServiceProcess'); RegisterServiceProcess (GetCurrentProcessid, 1); FreeElibrary (HNDL); Result: = true; endelseexit;

Q: How is the self copy method? A: The principle of this method is that the program is running first. If you continue to run, if you don't copy yourself to a specific directory, then run new Program, then exit the old program. Open Delphi, create a new project, write code in the window of the CREATE event: Procedure TFORM1.FormCreate (Sender: TOBJECT); var myname: string; beginmyname: = extractFileName (Application.exename); // Get file name if Application.exename <> getwindir myname dam // If the file is not in Windows / System / then ..begincopyFile (Pchar (Application.exename), Pchar (getWindir MyName), False; {copy yourself to Windows / System / Lower} Winexec (Pchar (getWindir MyName), SW_HIDE); // Running the new file application.terminate under Windows / System / under; // Exit End; End; where getWindir is a custom function, the function is Find a Windows / System / Path .Function getWindir: string; varbuf: array [0..max_path] of char; begingetsystemdirectory (buf, max_path); result: = BUF; if Result [length (result)] <> '/ 'Ten Result: = Result ' / '; END;

Q: How to avoid running multiple identical procedures while running more than a copy of multiple programs (saving system resources), the program generally can only run one. This further has several ways. Method is to find the same run when the program is running. If there is, you will immediately exit the program. Modify the DPR project file, modify the code between Begin and End is as follows: BeginApplication.initialize; if FindWindow ('TForm1', 'Form1 ') = 0 THEN BEGIN / / Do not find the code. When startup, you will be able to determine if it is already running through the window name. If it is, the original startup is turned off. "Ice" is in this way. The benefits of this are convenient to upgrade. It automatically covers the old version with a new version. Methods to modify DPR project files Usesforms, Windows, Messages, Unit1 in 'Unit1.Pas' {FORM1}; Q: How to make the program Windows starts automatically when starting? A: In order to automatically run when Windows is started, it can be implemented through six ways. "" Ice "uses a registry. Add Registry means Rewrite Create event window, the program rewritten as follows: procedure TForm1.FormCreate (Sender: TObject); const K = '/ Software / Microsoft / Windows / CurrentVersion / RunServices'; var myname: string; begin { Write by lovejingtao, http://lovejingtao.126.com} myname: = extractFileName (Application.exename); // Get file name if Application.exename <> getWindir myname dam // If the file is not In Windows / System / So .. BegIncopyFile (Pchar (Application.exename), Pchar (getWindir MyName), False); {// Put your own to Windows / System / Lower} Winexec (Pchar (Pchar (GetWindir MyName), SW_HIDE ); new file application.Terminate // run Windows / System / under; // exit end; with TRegistry.Create dotryRootKey: = HKEY_LOCAL_MACHINE; OpenKey (K, TRUE); WriteString ( 'syspler', application.ExeName); finallyfree ; End;

Q: How can I remove my own program? A: It's very simple, you can write a BAT file such as: a.bat del% 0, then remove A.BAT to the A.BAT!

Play an example: Friends who have used DOS should still remember the batch file, create a batch file a.bat, edit its content: DEL% 0, then run it, how? A.BAT removes yourself! ! ! Ok, we use it to "commit suicide"! Find an Exe executable, such as Abc.exe, create a batch file A.BAT, editing its contents :: ppdel abc.exeif exist abc.exe goto ppdel% 0 First run ABC.EXE, run A. BAT, then quit ABC.exe, you will find A.EXE and A.BAT! ! ! According to this idea, we can write a batch according to the file name in the program, and change the above ABC.EXE to your own EXE file name. Run Delphi, create a new project, add a button to the form, click on Button, write down the following code:

procedure TForm1.Button1Click (Sender: TObject); var Selfname, BatFilename, s1, s2: string; BatchFile: TextFile; beginSelfname: = Extractfilename (application.exename); // get their name EXE file BatFilename: = ExtractFilePath (Application. Exename) 'a.bat'; // Batch file name S1: = '@ del' SelfName; S2: = 'if exist' selfname 'goto pp'; assignfile (Batchfile, BatFileName); REWRITE (Batchfile) Writeln (Batchfile, ': PP'); Writeln (Batchfile, S1); Writeln (Batchfile, '@ del% 0'); Closefile (Batchfile); Winexec (Pchar (BatFileName), SW_HIDE ); // hide the window to run a.batapplication.terminate; // exit the program end; then our things are finished? NO! The above program principle is right, but if your program is running in a system directory such as a Windows Directory or Windows / System, etc., unless you open the directory to see it delete, it will not be removed at all. What should I do? Do not worry, we call out a function CreateProcess, its prototype is: BOOL CreateProcess (LPCTSTR lpApplicationName, // pointer to name of executable module LPTSTR lpCommandLine, // pointer to command line stringLPSECURITY_ATTRIBUTES lpProcessAttributes, // pointer to process security attributes LPSECURITY_ATTRIBUTES lpThreadAttributes , // pointer to thread security attributes BOOL bInheritHandles, // handle inheritance flag DWORD dwCreationFlags, // creation flags LPVOID lpEnvironment, // pointer to new environment block LPCTSTR lpCurrentDirectory, // pointer to current directory name lPSTARTUPINFO lpStartupInfo, // pointer to StartupInfo LPPROCESS_INFORMATION LPPROCESSINFORMATION / / POINTER TO Process_information); This function and OpenProcess, ReadProcessMemory, WriteProcessMemory use can be used to read and modify memory data, commonly used game modifiers are used. Since these are not the focus of this article, this is not described in detail, and interested readers can read the help files of Delphi itself. Creating a process with the CreateProcess function can perfect our "program suicide". Run Delphi, create a new project, add a button to the form, all code is as follows:

Unit unit1; interface

usesWindows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; typeTForm1 = class (TForm) Button1: TButton; procedure My_DeleteMe; // custom suicide process procedure Button1Click (Sender: TObject); private {Private declarations } public {public declarations}

Varform1: TFORM1;

IMPLEMentation

{$ R * .dfm}

Procedure tform1.button1click (sender: TOBJECT); beginmy_deleteme; end; procedure tform1.my_deleteme; // Program suicide // ----------------------- --------------------------------- Function GetShortName (Slongname: String): String; // Convert long file name varsShortName: string; nShortNameLen: integer; beginSetLength (sShortName, MAX_PATH); nShortNameLen: = GetShortPathName (PChar (sLongName), PChar (sShortName), MAX_PATH - 1); if (0 = nShortNameLen) thenbegin // handle errors ... end SETLENGTH (SSHORTNAME, NSHORTNAMELEN); Result: = sshortname; end; // --------------------------------- ---------------- varBatchFile: TextFile; BatchFileName: string; ProcessInfo: TProcessInformation; StartUpInfo: TStartupInfo; beginBatchFileName: = ExtractFilePath (ParamStr (0)) '$$ a $$. Bat '; assignfile (Batchfile, Batchfile; Writeln (Batchfile,': try '); Writeln (Batchfile,' del " getshortname (paramstr (0)) '"); Writeln (Batchfile , 'if est " getshortname (paramstr (0)) '" ' ' goto try '); Writeln (Batchfile,' del% 0 '); Writeln (Batchfile, 'Cls'); Writeln (BatchFile, 'exit'); CloseFile (BatchFile); FillChar (StartUpInfo, SizeOf (StartUpInfo), $ 00); StartUpInfo.dwFlags: = STARTF_USESHOWWINDOW; StartUpInfo.wShowWindow: = SW_Hide; if CreateProcess (nil, PChar (BatchFileName), nil, nil, False, IDLE_PRIORITY_CLASS, nil, nil, StartUpInfo, ProcessInfo) thenbeginCloseHandle (ProcessInfo.hThread); CloseHandle (ProcessInfo.hProcess); end; Application.Terminate; end; end.

Supplement: 1. The above batch of DEL% 0 is equivalent to del A.BAT, with del A.BAT, the batch file must be A.BAT, can be free to use Del% 0. 2, all programs run in PWIN98 Delphi5, Win2000 Delphi5. The title of this article is "Unloading of Installation and Uninstall", next time you will introduce you how to make your own installer with Delphi. I remember that there is a famous hacker that I never look for tool software, write one yourself if you need it. If we also hold this attitude, the programming level will be more and higher. Q: How to get the password in *******? A: Here is an example: // ********************************* ******************************* 8 // Password_dos.dpr, Chen Jingyi works // http: // lovejingtao. 126.com//lovejingtao@21cn.com//***************************************************** *********************8

Program password_dos; {$ apptype console} // setup program is a non-graphical interface

Useswindows, Messages;

Const S: boolean = true; // Circular Sign

VAR

Pass_edit_hwnd: hwnd; // Password window handle P: tpoint; // mouse pointer

Begin

Writeln; writeln ('*************************************************** *****************************); Writeln; WriteLn; WriteLn ('asterisk * Password Crack "; Writeln ( 'Usage: Move the mouse to the password box, the password will be automatically exactly!'); Writeln ('Press CTRL C exiting the program.

'); Writeln (' /// | ///////////// '); WriteLn (' (@ @) '); WriteLn (' -------- -------------- Oooo - (_) - oooo ------------------- '); Writeln (' | |); Writeln ('| If you find any problems during use, please contact me in time: |'); Writeln ('| Home: http://lovejingtao.126.com |'); Writeln ('| e-mail: lovejingtao@21cn.com |); Writeln (' | | '); Writeln (' | ooo Chen Jingyi 2000.07 | '); WriteLn (' ------------------------------ ------------ OOOO --- () -------------------- '); Writeln (' ()) / '); Writeln (' / ((_ / ' Writeln ('/ _)'); Writeln; WriteLn ('******************************** ****************************************); Writeln; While S <> False do begingetcursorpos (p); // check the mouse coordinates pass_edit_hwnd: = WindowFromPoint (p); // return a handle SendMessage (pass_edit_hwnd, EM_SETPASSWORDCHAR, 0,0); // send message SendMessage (pass_edit_hwnd, WM_PAINT, 0,0); / / SendMessage (pass_edit_hwnd, wm_killfocus, 0, 0); // Refresh window sendMessage (pass_edit_hwnd, wm_setfocus, 0, 0); // Sleep (1000); // delay 1000 milliseconds; END.

Q: How do I operate for registration? A: First: Uses registry; var r: TregistryR: = Tregistry.create; r.RootKey: = HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER Z.OpenKey ('Software / Microsoft', true); Then you can R.Readstring, R.Readinteger, R.WritString, R.Writeinteger, and the like. Form's oncreate and onclose two events write something, oncreate is to read the previously written content, onClose is written to change, the following is an example: put a Checkbox and Edit

Uses Windows, Messages, Sysutils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Stdctrls, Comctrls, INIFILES; // INIFILES Don't forget to add

procedure TForm1.FormClose (Sender: TObject; var Action: TCloseAction); begin With TINIFile.Create ( 'a.ini') do // Create a.ini begin WriteBool ( 'MySetting', 'CheckBox1_Checked', CheckBox1.Checked); {Save to the checkbox1_checked subkey under MySetting, then write the checkbox1 to write it into} WritestRing ('MySetting', 'Edit1_Text', Edit1.Text); // Same on End; End;

Procedure TForm1.FormCreate (Sender: TOBJECT); // Read settings in a.ini file Begin with tinifile.create ('a.ini') do // Open the created A.ini Begin CheckBox1.checked: = ReadBool ('MySetting', 'CheckBox1_Checked', false); {is the same as above, here is a write method for reading ReadBool and WriteBool is two BOOL values.} Edit1.Text: = ReadString ('MySetting', ' Edit1_text ',' '); // 同 End;

Q: How can I make a running program automatically maximize? A: This is an example: VarhwndWindow: hwnd; beginhwndWindow: = FindWindow (nil, 'delphi skill'); // Delphi skills change to your maximization window Titu. IF HWNDWINDOW <> 0 THEN / / I don't equal 0, find this form PostMessage (hwndwindow, wm_syscommand, sc_maximize, 0); // Send a maximum message (sc_maximize) to this form with postMaximize // ******************************************************** ****** // Except PostMESSAGE (HWndWindow, WM_Close, 0, 0); To close // If you need to make the program dynamically change to maximize the program dynamism; // form1 You have to maximize the window name! // Several nouns: 1.hWnd is the meaning of the handle, only get the form of the form to control it 2.FindWindow is the meaning of finding the form. 3.NIL is empty pointer. 4.postMessage Send A message gives a found window handle. Q: How to make the program suspend a period of time during the execution? A: To make the program in the run, you can use the Sleep this keyword, below is an example procedure tForm1.Button1click (Sender: TOBJECT); VARH, M, S, MS: Word; Beginedit1.Text: = DateTimetostr (now); Sleep (2000); // 2000 represents 2 microsecond Edit2.Text: = DATETITIMETOSTR (NOW); Decodetime (adodatetime (edit2.text) -strtodatetime (edit1.text), H, M, S, MS); showMessage (Format ('Hour:% D', [H]) Format ('Minute:% D', [M]) Format ('second:% d', [s]) format ('microseconds:% d', [ms])); end; //, this is also a good time Examples of example report time: // First definition: Varpresent: tdatetime; // Define Date and Time Beginyear, Month, Day, Hour, min, sec, msec: word; // Definition Annual Monthly Monthly Subtitecock Decodetime (Present, Hour, min, sec, msec); // proposed a small second microsecond, TDataTime mode DECODEDATE (Present, Year, Month, day); // Submit the Year and Moon, TDataTime mode Label1.caption : = 'Today Is Day' INTOSTR (MONTH) 'of year' INTOSTOSTR (YEAR); // Display Label2.caption: = 'Time Is Minute' INTOSTR MIN) 'of Hour' INTOSTR (HOUR); // Displays END;

Q: How do I join a flash animation on the window? A: First put the flash animation on an HTM file, then call the HTM file to the window as follows: Procedure TFORM1.FormCreate (Sender: TOBJECT); VARURL: Olevariant; BeginURL: = extractfilepath (application.exename) 'fla.htm'; webbrowser1.naviGate2 (URL); end; // To add a webbrowser control Q: How can I get jump to the web page in the program? A: The example is as follows: Procedure TForm1.ToolButton5Click (Sender: Tobject); BeginsHellexecute (Http://go.163.com/delphimyself '), NIL, NIL, SW_SHOWNORMAL); END;

Q: How do I get the directory of this program? A: example as follows: procedure tform1.formcreate (sender: TOBJECT); beginedit1.text: = extractFilePath (Application.exename); end; // extractFilePath (Application.exename); get it File path, Application.exenane // extractFileName (Application.exename); get file name, extractfilename

Q: How do I close Windows? A: This can close Windows9x system EXITWINDOWSEX (EWX_SHUTDOWN, 0);

Q: How to get a Windows installation directory? A: Here is an example: procedure tform1.button1click (sender: TOBJECT); var Dir: array [0..255] of char; begin getWindowsDirectory (Dir, 255); Edit1.Text : = STRPAS (DIR); END; // Define a DIR array is a char type / / then getWindowsDirectory (Dir, 255); // Displayed with the strPas function to display // There is also an example can be achieved: Procedure tForm1.Button1Click (Sender: Tobject); VarwinPath: Pchar; BegingeTMem (WinPath, 255); GetWindowsDirectory (WinPath, 255); Edit1.Text: = WinPath; END;

**********************

Determine whether Item is selected: for i: = 0 to listbox.items.count-1 do if listbox.selected [i] The begin ShowMessage ('has item selected'); break; end allows the first item selected: Listbox .Itemindex: = 0;

***************************** Gets the hard disk serial number

Procedure TForm1.FormCreate (Sender: TOBJECT); VARDW, DWTEMP1, DWTEMP2: DWORD; P1, P2: Array [0..30] of char; begingeTVolumeInformation (pchar ('c: /'), p1, 20, @ dw, DWTEMP1, DWTEMP2, P2, 20); Edit1.Text: = INTTOHEX (DW, 8); // Series number end; ********************** **** Drag the control in the program

Write in the mousedown of the control:

ReleaseCapture; SendMessage (Panel1.handle, WM_SYSCOMMAMMAND, $ F012, 0); Also change $ F012 value will have a lot of other functions $ f001: Changing the LEFT size $ f002: Change the control of the Right size $ F003: Change the control Top size $ f004: Change the control of the Button size $ f007: Control left zoom in to zoom in to zoom in a $ f008: Right to zoom in to zoom in $ f009: Dynamic mobile control ****************************** **** Win98 hidden process method

Unit unit1;

Interface

Uses Windows, Messages, Sysutils, Variants, Classes, Graphics, Controls, Forms, Dialogs

TYPE TFORM1 = Class (TFORM) Procedure formcreate (sender: TOBJECT); private {private declarations} end;

Var Form1: TFORM1;

ImplementationFunction RegisterServiceProcess (DWProcessID, DWTYPE: Integer): Integer; stdcall; External

'Kernel32.dll';

{$ R * .dfm}

procedure TForm1.FormCreate (Sender: TObject); begin SetWindowLong (Application.Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW); RegisterServiceProcess (GetCurrentProcessID, 1); end; end dpr Further in inside Application.CreateForm (TForm1, Form1); followed by. Application.showmainform: = false;

************************************* Sendmessage (Handle, WM_LButtonDBLCLK) , 0, 0); SendMessage (Handle, WM_Close, 0, 0); Start start menu SendMessage (Application.Handle, Wm_SysCommand, SC_TASKLIST, 0);

*************************** Date Time Operation

ShowMessage ('YYYY', NOW); // Year ShowMessage (FormatDateTime ('mm', now)); // month showMessage (FormatDateTime ('DD', NOW)); // 日 ShowMessage (FormatorTime HH ', now); // ShowMessage (Formator (' NN ', NOW)); // Division ShowMessage (FormatDateTime (' NN ', NOW)); /// Second ShowMessage (FormatorTime (' Zzz ', NOW) ); // millisecond

**********************************

Winexec (Pchar ('Net Start W3SVC'), SW_HIDE); is to perform NET START W3SVC

*************************** MediaPlayer control button

procedure TForm1.FormCreate (Sender: TObject); begin MediaPlayer1.Open; MediaPlayer1.Play; MediaPlayer1.EnabledButtons: = [btPause, btStop, btNext, btPrev, btStep, btBack]; end; procedure TForm1.MediaPlayer1Click (Sender: TObject; Button : TMPBtnType; var DoDefault: Boolean); begin case Button of btPlay: begin MediaPlayer1.Play; MediaPlayer1.EnabledButtons: = [btPause, btStop, btNext, btPrev, btStep, btBack]; end; btPause: begin if MediaPlayer1.Mode = mpPaused then begin MediaPlayer1.Play; MediaPlayer1.EnabledButtons: = [btPause, btStop, btNext, btPrev, btStep, btBack]; end else if MediaPlayer1.Mode = mpPlaying then begin MediaPlayer1.Pause; MediaPlayer1.EnabledButtons: = [btPlay, btPause, btStop , btnext, btprev, btstep, btback]; end; end; btstop: begin mediaplayer1.stop; MediaPlayer1.enableDButtons: = [btplay, btnext, btprev, btstep, btback]; end; bt Next: begin MediaPlayer1.Next; MediaPlayer1.EnabledButtons: = [btPlay, btNext, btPrev, btStep, btBack]; end; btPrev: begin MediaPlayer1.Previous; MediaPlayer1.EnabledButtons: = [btPlay, btNext, btPrev, btStep, btBack]; end; btStep: begin MediaPlayer1.Step; MediaPlayer1.EnabledButtons: = [btPlay, btNext, btPrev, btStep, btBack]; end; btBack: begin MediaPlayer1.Back; MediaPlayer1.EnabledButtons: = [btPlay, btNext, btPrev, btStep, btBack End;

*************************** Domain Dynamic Generating Batch File

Var Hndfile: Thandle; Begin Hndfile: = filecreate ('deljpg.bat'); FileWrite (Hndfile, 'del * .txt' # 13 # 10, Length ('del * .txt' # 13 # 10)); FileWrite (Hndfile, 'del deljpg.bat', length ('del deljpg.bat')); fileclose (hndfile); Winexec (Pchar ('./ deljpg.bat'), sw_hide); End above program generated batch processing The file name is deljpg.bat is Del * .txtdel deljpg.bat plus one

Procedure TForm1.Button1Click (Sender: Tobject); var f: textfile; ifileHandle: Integer; Begin ifileHandle: = FileCreate ('f: /deljpg.bat'); FileClose (ifilehandle);

AssignFile (f, 'f: /deljpg.bat'); append (f); WriteLn (f, 'del f: /' edit1.text '* .txt'); Writeln (f, 'del f: / Deljpg.bat '); Closefile (f);

Winexec (PCHAR ('f: /deljpg.bat'), sw_hide);

***************************** Open the new window to make the previous window in gray shape Form2.ShowModal

****************************************************************** Procedure TFORM1.FormCreate (Sender: TOBJECT); Begin

Edit2.text: = extractFilePath (paramstr (0)); // Get the program running directory path edit1.text: = (Application.exename); // Get the full path to the program run

END;

************************************* If the hotkey is required to use in this program Method with STUWE: add three anctions such as action1, set its action1.shortcut for F1 at its procedure tform1.action1execute (sender: TOBJECT); begin shellexecute (....); END; the other two

If you want to see the following: RegisterhotKey function original and instructions: BOOL registerhotkey (hwnd hwnd, // window to receive, // identifier of hot key uint fsmodifiers, / / key-modifier flags uint vk // virtual-key code); Parameter ID is a ID value defined by your own, and the value is required for a thread. It must be within the 0x0000 - 0xBFFF range, and the value is required for DLL. Within 0xc000 - 0xffffffffffffffffffffffffffffffffffff, this value must uniquely parameter fsmodifiers indicate that the button is combined with the hotkey, which can be used as: mod_alt mod_control mod_win mod_shift parameter VK specifies the virtual key code of the hotkey

First (for example): registerhotKey (HANDLE, GLOBALADDATOM ('Hot Key'), MOD_ALT, VK_F12); then declare a function (process) in Form: Procedure Hotkey (Var Msg: tMESSAGE); Message WM_HOTKEY; process is as follows: Procedure TForm1.HotKey (VAR MSG: TMESSAGE); Begin if (msg.lparamhi = vk_f12) and (msg.lparamlo = mod_alt) THEN Begin Form1.Show; set; End; End; This, no matter where you are The window will appear. Of course, you have to globaldeletetom;

Unit unit1;

Interface

Uses Windows, Messages, Sysutils, Classes, Graphics, Controls, Forms, Dialogs

type TForm1 = class (TForm) procedure FormCreate (Sender: TObject); procedure FormDestroy (Sender: TObject); private {Private declarations} aatom: atom; procedure hotkey (var msg: tmessage); message wm_hotkey; public {Public declarations} end ;

Var Form1: TFORM1;

IMPLEMENTATION

{$ R * .dfm}

Procedure TForm1.FormCreate (Sender: Tobject); Begin aat: = GlobalAddatom ('Hot Key'); RegisterhotKey (Handle, Aatom, Mod_alt, VK_F12);

Procedure TFORM1.HOTKEY (VAR MSG: TMESSAGE); Begin if (msg.lparamhi = vk_f12) and (msg.lparamlo = mod_alt) THEN SETFOREGROUNDOW (HANDE);

Procedure TFORM1.FORMDESTROY (Sender: TOBJECT); Begin GlobalDeleTeatom (aat);

End. full source code http://www.aidelphi.com/6to23/docu/Hotkey.zip The following is the example procedure tForm1.FormCreate (Sender: TOBJECT); VAR TMPID: INTEGER; begin tmpid: = GlobalFindatom ('myhotkey') If Tmpid = 0 THEN / / Find global atoms. If the return value is not 0, then this global atom has been registered; ID: = GlobalAddatom ('myhotkey') Else ID: = TmpID;

TMPID: = GlobalFindatom ('myhotkey1'); if tmpid = 0 THEN ID1: = GlobalAddatom ('myhotkey1') else id1: = tmpid;

TMPID: = GlobalFindatom ('myhotkey2'); if tmpid = 0 THEN ID2: = GlobalAddatom ('myhotkey2') Else ID2: = Tmpid; RegisterhotKey (Handle, ID, MOD_CONTROL, VK_F1); // Register hot key: Ctrl F1 RegisterhotKey (Handle, ID1, Mod_Control, VK_F2); // Register hotkey: Ctrl F2 RegisterhotKey (Handle, ID2, MOD_CONTROL, VK_F3); // Register Hotkey: Ctrocedure TFORM1.MMDESTROY (Sender: TFORM1.MMDESTROY (Sender: TOBJECT) Begin UnregisterhotKey (Handle, ID); // Release the hotkey Ctrl F1 UnregisterhotKey (Handle, ID1); // Release the hotkey Ctrl F2 unregisterhotKey (Handle, ID2); // Release the hotkey Ctrl F3 GlobalDeleTeatom (ID) ); // Delete global atomic ID GlobalDeleTeatom (ID1); // Delete global atomic id1 globaldeleTeatom (ID2); // Delete global atomic ID2END;

Procedure TForm1.WMhotKey (var msg: twmhotkey); begin if msg.hotkey = ID THEN / / hotkey Ctrl F1 message. ShowMessage ('Ctrl F1!') Else if msg.hotkey = id1 Then // Hotkey Ctrl F2 message. ShowMessage ('Ctrl F2!') Else if msg.hotkey = id2 THEN / / hotkey Ctrl F3 message. ShowMessage ('Ctrl F3!'); End; ***** ***************************** The judgment program runs if FindWindow (main program class, main program title) = 0 Then/ find this program Begin ShowMessage ('main program is not run "; application.terminate;

****************************** Get classes at the mouse position

procedure TForm1.Timer1Timer (Sender: TObject); varClassName: PChar; atCursor: TPoint; hWndMouseOver: HWND; // handle mouse Text: PChar; beginGetCursorPos (atCursor); // get the mouse coordinates hWndMouseOver: = WindowFromPoint (atCursor); / / mouse to obtain and handle position GetMem (ClassName, 100); GetMem (Text, 255); tryGetClassName (hWndMouseOver, ClassName, 100); SendMessage (hWndMouseOver, WM_GETTEXT, 255, LongInt (Text)); Label_ClassName.Caption: = 'class ClassName: ' string (classname); edit1.text: = string (text); FinallyFreeMem (classname); FreeMem (Text); end;

**************************** Breakpoint resume

If you use the ICS control, httpcli.contentRangeBegin: = '100' indicates that httpcli.contentRangeend: = '' indicates from 100 to end httpcli.contentRangeend: = '200' to end the 200-byte

If you use the TNMHTTP control in the OnAbouttosend event, write: nmhttp1.sendHeader.values ​​['Range']: = 'BYTES = 100-' indicates that start downloading from 100 bytes to the last nmhttp1.sendheader.values ​​['Range']: = 'bytes = 100-200' indicates that start downloading from 100 bytes to 200 bytes ending *************************************** Procedure TFORM1.BUTTON6CLICK (Sender: TOBJECT); VARF: TSEARCHREC BeginfindFirst ('a.doc', faanyfile, f); f); nmftp.docommand ('REST' INTSTOCMMAN); NMFTP.DOWNLOADRESTORE ('a.doc', 'a.doc') END; this is the code to be transmitted by TNMFTP.

************************************* Delphi uses the Sender parameters to reuse

One of the features of object-oriented programming tools is to increase the code reuse, as a new generation visual development tool, the code reuse in Delphi is quite high. We know that in Delphi, most of the program code corresponds directly or indirectly, this program is called an event handle, which is actually a process. From the application's engineering to forms, components and programs, Delphi emphasizes the reuse of each level during its development process, which can reach the program reuse by writing event handles commonly used by certain components. You can point the process handle of the A event to the processing handle of the B event on the Events page of the property window, so that the A event and the B event share a process segment, which reaches the purpose of reuse. If the shared block is independent of control, such as ShowMessage ('Hello, World'), this sharing is the easiest. However, in general, the sharing between code segments is related to the control of the event, and it is necessary to make a corresponding processing according to the type of control. At this time, the sender parameter is used. The beginning of each process is similar to Procedure TForm1formClick (Sender: TOBJECT); where Sender is a TOBJECT type parameter, which tells Delphi which control receives this event and calls the corresponding process. You can write a single event handle handle to process multiple components through the Sender parameter and if ... then ... statement or CASE statement. The value of the component or control of the event has been assigned to the Sender parameter, one of the uses of this parameter is that the reserved word is can be used to test the Sender to find the type of component or control that calls this event handles handle. For example, the handle of the edit box and the Click event of the edit box and the label is directed to the XXX process of the form, the edit box, and the label have different reactions to the Click event: procedure tform1xxx (sender: TOBJECT); Begin IF (sender if Tedit) The showMessage ('this is a editbox'); if (sender is tlabel) THOWMESSAGE ('this is a label'); END; the second purpose of the sender parameter is to combine the AS operator type conversion, will certain Sub-class for derived a parent class forced into this parent class. For example, there is a TEDIT class control and a TMEMO control in the form. They are actually derived from the TCUStomedit class. If you want to provide the same processing for one of the two, you can point the two event handles to custom procedures YYY: Procedure TForm1.Yyy (Sender: TPJECT) .Text: = 'this is some demo text'; end; in the process, the AS operator is forced to convert TEDIT classes and TMEMO classes into TCUStomedit classes. The property is assigned to the attribute of the TCUStomedit class. Note that this conversion must comply with the hierarchical relationships in Delphi. Using the Sender parameter can process multiple controls through a single process segment, truly embodying the Delphi object-oriented reuse. **************************** Window gradually appears animatewindow (Handle, 1000, AW_Center);

*********************************** Delphi embedded

Function cyclecount: int64; ASM DB $ 0F DB $ 31nd;

********************** Read the BIOS Name Date Serial number read the BIOS name date serial number, this program is shortest! Test in D5! WITH MEMO1.LINES DO Begin Add (PCHAR (PTR ($ FE061))))))))))); add ('mainboardbioscopyright:' ^ i string (PCHAR (Ptr (PTR ($ FE091))))) ); Add ('mainboardbiosdate:' ^ i string (PCHAR (PTR ($ FFFF5)))))); add ('mainboardbiosserialno:' ^ i string (PCHAR (PTR (PTR ($ FEC71))); ///

Read the motherboard information: Motherboard Name: String (PCHAR (Ptr ($ FE061)))); copyright: String (Ptring (Ptr ($ FE091))); Date: String String (PCHAR (PTR ($ fec71));

*********************** At 20,000 shutdown at 20,000, it is not like directly calling the exitwindows function in 98, you first open with the openprocessToken function. Access signaling related to the process then exits Win2000 with the exitwindow function.

The following this procedure for reference: var hToken: THandle; tkp: TOKEN_PRIVILEGES; otkp: TOKEN_PRIVILEGES; dwLen: Dword; begin if OpenProcessToken (GetCurrentProcess, TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY, hToken) then begin LookupPrivilegevalue (Nil, 'SeShutdownPrivilege', tkp.Privileges [0] .luid); tkp.privilegegount: = 1; Tkp.privileges [0] .attributes: = se_priVilege_enabled; AdjustTokenPrivileges (HTOKEN, FALSE, TKP, SIZEOF (TKP), OTKP, ​​DWLEN; IF (getLastError () = ERROR_SUCCESS) THEN BEGIN EXITWINDOWSEX (EWX_Poweroff, 0); // Shutdown end; end; end;

*************************** Analog keyboard keys Shift A 'is changed to delphi is:

keybd_event (VK_SHIFT, 0, KEYEVENTF_EXTENDEDKEY 0,0); keybd_event (65,0, KEYEVENTF_EXTENDEDKEY 0,0); keybd_event (65,0, KEYEVENTF_EXTENDEDKEY KEYEVENTF_KEYUP, 0); keybd_event (VK_SHIFT, 0, KEYEVENTF_EXTENDEDKEY KEYEVENTF_KEYUP, 0 );

*****************************************************************************

Popked the optical drive McIndstring ('set cdaudio door open wait', nil, 0, handle); Turn off the CD-ROM MCISENDSTRING ('set cdaudio door closed Wait', NIL, 0, Handle); *********** *****************************;............................................................................................................................................. .

Procedure TForm1.WmsysCommand (var Msg: TwmsysCommand); Begin if msg.cmdtype <> sc_close dam inheritede;

********************************************************************************* Good is to write less! (Writing Better is Writing Less) "Answer: The following command can be executed directly in Windows running window, you have to use in Delphi: Winexec (Pchar ('Abcd'), sw_show);" ABCD "represents one of the following commands:" Rundll32 shell32, control_rundll "- Run the control panel" Rundll32 shell32, openas_rundll "- Open" Open mode "window" Rundll32 Shell32, Shellabouta Info-Box "- Open" About "Window" Rundll32 shell32, Control_RunDLL desk.cpl "- open the" display properties "window" rundll32 user, cascadechildwindows "- all layered window" rundll32 user, tilechildwindows "- minimize all child windows" rundll32 user, repaintscreen "- to refresh the desktop" rundll32 shell, shellexecute Explorer "- Re-run Windows Explorer" Rundll32 Keyboard, Disable "- Lock keyboard" Rundll32 Mouse, Disable "- Mouse Failure" Rundll32 User, SwapmouseButton "- Exchange Mouse Button" Rundll32 User, SetCursorpos "- Set the mouse location as (0," 0) "Rundll32 User, WNETCONNECTDIALOG" - Open "Rundll32 User, WnetdisconnectDialog" - Open "Runl12 User, DisableoemLayer" - Display BSOD window, (BSOD) display BSOD window, (BSOD) = Blue Screen of DEATH Blue screen "Rundll32 Diskcopy, DiskCopyRundll" - Open Disk Copy Window "Rundll32 Rnaui.dll, Runizard" - Run "Internet Connection Wizard, if added The upper parameter "/ 1" is Silent mode "Rundll32 Shell32, SHFORMATDRIVE" - Open "Format Disk (a)" window "Rundll32 shell32, shexitWindowSex -1" - cold start Windows Explorer "Rundll32 shell32, ShexitWindowSex 1" - shutdown " rundll32 shell32, SHExitWindowsEx 0 "- reverse the current user" rundll32 shell32, SHExitWindowsEx 2 "Windows9x QUICK rESTART" rundll32 krnl386.exe, exitkernel "- forced to quit Windows 9x (no confirmation)" rundll rnaui.dll, RnaDial "MyConnect" - run " Network Connection "Dialog" Rundll32 MSPrint2.dll, Rundll_PrintTestPage "

- Select the printer and print test page "Rundll32 User, setcaretblinktime" - Set the cursor flash speed "Rundll32 User, SetDoubleClickTime" - Test Mouse Double-click Speed ​​"Rundll32 Sysdm.cpl, InstallDevice_Rundll" - Search Non-PNP Device ******** *********************************** MessageBeep (0); // Sound card issued a be sound Windows.beep (2000, 2000); // PC The speaker makes a be sound, it is very scary / / the previous one is the frequency, the latter is delayed, 98 will ignore

*********************************************************** ***** Get available memory and system resource Procedure TVERSION.FORMCREATE (Sender: TObject); Var MS: TmemoryStatus; Begin GlobalMemoryStatus (MS); label5.caption: = 'Available Memory:' Formatfloat ('#, ## # "Kb", ms.dwtotalphys / 1024); label6.caption: = 'System Resource' Format ('% D %%', [Ms.dwMemoryLoad]) 'Available';

*********************************************************** *** Check if the program does not send Function ISBUSY (Processid: Integer): Integer; Var Ph: Thandle; Begin Ph: = OpenProcess (process_all_access, false, processid); if ph <> 0 THEN BEGIN IF WAITFORINPUTIDLE (pH, 10 ) = Wait_timeout the result: = 1 else result: = 0; CloseHandle (pH); ELSE RESULT: = -1; END;

**************************** Trivial mouse trivial keyboard - ******* - * - ** ****************

Var A: TRECT; temp: integer; begin {shield system key} SystemParametersInfo (spi_screensaverrunning, 1, @temp, 0); A: = RECT (0, 0, 5, 5); {Lock mouse in a certain area, most Key Lock in your window} clipcursor (@a); end; {Lock} Begin SystemParametersInfo (spi_screensaverrunning, 0, @temp, 0); ClipCursor (NIL);

***************************** * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * procedure TForm1.Button1Click (Sender: TObject); var dc: hdc; mycanvas: TCanVas; mybitmap: TBitmap; beginapplication.Minimize; mycanvas: = TCanvas.Create; mybitmap: = tbitmap .Create; dc: = getDC (0); trymycanvas.handle: = DC; with screen dobegin mybitmap.width: = width; mybitmap.height: = height; mybitmap.canvas.copyRect (RECT (0, 0, Width, HEight ), Mycanvas, RECT (0, Width, Height); image1.picture.bitmap.assign (mybitmap); end; finally releasedc (0, dc); mycanvas.free; mybitmap.free; end; application.restore ; end; *************************** ACCESS skill sets of: ysai reprint please indicate the source and keep the article intact

1.Delphi ACCESS database (established .mdb file, compressed database) The following code is tested under Win2K, D6, MDAC2.6, compiled, compiled programs run in the Win98 second edition without Access Environment. // declaration connection String const sconnectionstring = 'provider = microsoft.jet.Oledb.4.0; data source =% s;' 'Jet OLEDB: Database Password =% s;';

/ / =========================================================================================================================================================================================== ===================================== // procedure: getTemppathFileName // Author: ysai // Date: 2003-01-27 // Arguments: (none) // RESULT: STRING / / ======================================== ======================================= ======================================================================================================= File Name Var Spath, Sfile: Array [0..254] of char; begin getTemppath (254, spath); GetTempFileName (spath, '~ sm ", 0, sfile); result: = sfile; deletefile (Result); end ;

/ / =========================================================================================================================================================================================== ============================= // procedure: createaccessFile // Author: ysai // Date: 2003-01-27 // Arguments: filename: string; password: String = '' // Result: Boolean // =============================== ================================================================================================================================================================================================================== # : String; PassWord: string = ''): boolean; // build Access file, if the file exists fails var STempFileName: string; vCatalog: OleVariant; begin STempFileName: = GetTempPathFileName; try vCatalog: = CreateOleObject ( 'ADOX.Catalog' ); vCatalog.Create (format (sConnectionString, [STempFileName, PassWord])); result: = CopyFile (PChar (STempFileName), PChar (FileName), True); DeleteFile (STempFileName); except result: = false; end; end ;

/ / =========================================================================================================================================================================================== ===================================== // procedure: CompactDatabase // Author: ysai // Date: 2003-01-27 // Arguments: AFILENAME, APASSWORD: STRING / / RESULT: BOOLLAN / / ==================================== ================================================== Function CompactDatabase (AfileName, Apassword: String) : boolean; // compression and repair the database, covering the source file var STempFileName: string; vJE: OleVariant; begin STempFileName: = GetTempPathFileName; try vJE: = CreateOleObject ( 'JRO.JetEngine'); vJE.CompactDatabase (format (sConnectionString, [ aFileName, aPassWord]), format (sConnectionString, [STempFileName, aPassWord])); result: = CopyFile (PChar (STempFileName), PChar (aFileName), false); DeleteFile (STempFileName); except result: = false; end; end 2. The following SQL statements should be considered in the SQL statement in the Access XP in the query of Access XP. : The self-adding field is declared with a Counter. The field name is the field of the keyword, which is enclosed in square brackets, and the numbers are also feasible as a field name.

Establish an index: The following statement establishes repeatable index Crete index idate on tab1 on the DATE column of Tab1; after completion of the field Date index attribute displayed as - there is (have repetition). The following statement is in Tab1 The Name column creates non-repeatable index Create Unique Index INAME ON TAB1 (Name); Field Name Index Attributes in Access Dianced (None Duplicate). Access Statements in Access and SQL Series Comparison: SQL Server Update Update Statement: Update Tab1 Set A.Name = B.Name from Tab1 A, Tab2 B Where A.Id = B.ID; SQL statement of the same function should be UPDATE TAB1 A, TAB2 B Set a.name = B in Access. Name where a.id = B.ID; ie: The Update statement in Access does not have a FROM clause, and all references are listed after the UPDATE keyword. In the above example, if the TAB2 is not a table, but a query, example : Update Tab1 A, (Select ID, Name from Tab2) B Set A.Name = B.Name Where A.Id = B.ID;

Access multiple different access databases - use in clauses in SQL: SELECT A. *, B. * From Tab1 a, Tab2 b in 'db2.mdb' where a.id = B.ID; SQL statement query Tab2 in the Tab1 and DB2.mdb (current folder) in the current database is associated with the ID. Disadvantages - External databases cannot with password.

Accessing other ODBC Data Source in Access Squate in Access SQL Server Data Select * from Tab1 In [ODBC] [ODBC; Driver = SQL Server; UID = SA; PWD =; Server = 127.0.0.1; Database = Demo The complete parameters of the external data source connection properties are: [ODBC; Driver = Driver; Server = Server; Database = Database; UID = USER; PWD = user; pwd = password;] where driver = driver can be in the registry hkey_local_machine / software / Software /Odbc/odbcinst.ini/ found

Access support child inquiry

Access supports external connections, but does not include complete external join, such as supporting Left Join or Right Join but does not support Full Outer Join or Full Join

Date in Access Note: Date time separator in Access is # instead of quotation marks Select * from tab1 where [date]> # 2002-1 #; I use Sql.Add in Delphi. * From Tab1 where [Date]> #% s #; ', [DateTostr (date)]));

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

New Post(0)