DELPHI basic development skills
◇[DELPHI] Copy files from Network Neighborhood
usesshellapi;
copyfile(pchar('newfile.txt'),pchar('//computername/direction/targer.txt'),false);
◇[DELPHI] produces mouse drag effect
Implemented through MouseMove event, DragOver event, EndDrag event, such as LABEL on PANEL:
varxpanel,ypanel,xlabel,ylabel:integer;
PANEL's MouseMove event:xpanel:=x;ypanel:=y;
PANEL's DragOver event:xpanel:=x;ypanel:=y;
LABEL's MouseMove event:xlabel:=x;ylabel:=y;
LABEL's EndDrag event: label.left:=xpanel-xlabel;label.top:=ypanel-ylabel;
◇[DELPHI] Obtain WINDOWS directory
usesshellapi;
varwindir:array[0..255]ofchar;
getwindowsdirectory(windir,sizeof(windir));
Or read from the registry, location:
HKEY_LOCAL_MACHINE/Software/Microsoft/Windows/CurrentVersion
SystemRoot key, obtained as: C:/WINDOWS
◇[DELPHI] Draw lines on FORM or other containers
varx,y:array[0..50]ofinteger;
canvas.pen.color:=clred;
canvas.pen.style:=PSDash;
form1.canvas.moveto(trunc(x[i]),trunc(y[i]));
form1.canvas.lineto(trunc(x[j]),trunc(y[j]));
◇[DELPHI] string list usage
vartips:tstringlist;
tips:=tstringlist.create;
tips.loadfromfile('filename.txt');
edit1.text:=tips[0];
tips.add('lastlineadditionstring');
tips.insert(1,'insertstringatNO2line');
tips.savetofile('newfile.txt');
tips.free;
◇[DELPHI]Simple clipboard operation
richedit1.selectall;
richedit1.copytoclipboard;
richedit1.cuttoclipboard;
edit1.pastefromclipboard;
◇[DELPHI] About file and directory operations
Chdir('c:/abcdir');Go to directory
Mkdir('dirname');Create directory
Rmdir('dirname'); delete directory
GetCurrentDir;//Get the current directory name, without '/'
Getdir(0,s);//Get the working directory name s:='c:/abcdir';
Deletfile('abc.txt');//Delete file
Renamefile('old.txt','new.txt');//File rename
ExtractFilename(filelistbox1.filename);//Get the file name
ExtractFileExt(filelistbox1.filename);//Get the file suffix
◇[DELPHI] Process file attributes
attr:=filegetattr(filelistbox1.filename);
if(attrandfaReadonly)=faReadonlythen...//read-only
if(attrandfaSysfile)=faSysfilethen...//System
if(attrandfaArchive)=faArchivethen...//Archive
if(attrandfaHidden)=faHiddenthen...//Hide
◇[DELPHI]Execute files outside the program
WINEXEC//Call executable file
winexec('command.com/ccopy*.*c:/',SW_Normal);
winexec('startabc.txt');
ShellExecute or ShellExecuteEx//Start the file association program
functionexecutefile(constfilename,params,defaultDir:string;showCmd:integer):THandle;
ExecuteFile('C:/abc/a.txt','x.abc','c:/abc/',0);
ExecuteFile('http://tingweb.yeah.net','','',0);
ExecuteFile('mailto:[email protected]','','',0);
◇[DELPHI] Get the name of the process running on the system
varhCurrentWindow:HWnd;szText:array[0..254]ofchar;
begin
hCurrentWindow:=Getwindow(handle,GW_HWndFrist);
whilehCurrentWindow<>0do
begin
ifGetwindowtext(hcurrnetwindow,@sztext,255)>0thenlistbox1.items.add(strpas(@sztext));
hCurrentWindow:=Getwindow(hCurrentwindow,GW_HWndNext);
end;
end;
◇[DELPHI]About embedding of assembly
AsmEnd;
EAX, ECX, and EDX can be modified at will; ESI, EDI, ESP, EBP, and EBX cannot be modified.
◇[DELPHI]About type conversion function
FloatToStr//Floating point to string
FloatToStrF//Formatted floating point to string
IntToHex//Integer to hexadecimal
TimeToStr
DateToStr
DateTimeToStr
FmtStr//Output a string in the specified format
FormatDateTime('YYYY-MM-DD,hh-mm-ss',DATE);
◇[DELPHI]String procedures and functions
Insert(obj,target,pos);//The string target is inserted at the position of pos. If the insertion result is greater than the maximum length of the target, the extra characters will be truncated. If Pos is outside 255, an operation error will occur. For example, st:='Brian', then Insert('OK',st,2) will change st to 'BrOKian'.
Delete(st,pos,Num);//Delete a substring of Num (integer) characters starting from the pos (integer) position in the st string. For example, st:='Brian', then Delete(st,3,2) will become Brn.
Str(value,st);//Convert the numerical value (integer or real type) into a string and put it in st. For example, when a=2.5E4, str(a:10,st) will make the value of st be '25000'.
Val(st,var,code);//Convert the string expression st into the corresponding integer or real value and store it in var. St must be a string representing a numerical value and comply with the rules for numerical constants. During the conversion process, if no error is detected, the variable code is set to 0, otherwise it is set to the position of the first error character. For example, st:=25.4E3, x is a real variable, then val(st,x,code) will make the X value 25400 and the code value 0.
Copy(st.pos.num);//Returns a substring starting at position pos (integer) in the st string and containing num (integer) characters. If pos is greater than the length of the st string, an empty string will be returned. If pos is outside 255, a runtime error will occur. For example, st:='Brian', then Copy(st,2,2) returns 'ri'.
Concat(st1,st2,st3...,stn);//Concatenate the strings represented by all independent variables in the order given, and return the concatenated value. If the length of the result is 255, a runtime error will occur. For example, st1:='Brian',st2:='',st3:='Wilfred', then Concat(st1,st2,st3) returns 'BrianWilfred'.
Length(st);//Returns the length of the string expression st. For example, st:='Brian', then the return value of Length(st) is 5.
Pos(obj, target);//Returns the position where the string obj appears for the first time in the target string target. If target does not have a matching string, the return value of the Pos function is 0. For example, target:='BrianWilfred', then the return value of Pos('Wil',target) is 7, and the return value of Pos('hurbet',target) is 0.
◇[DELPHI]About handling the registry
usesRegistry;
varreg:Tregistry;
reg:=Tregistry.create;
reg.rootkey:='HKey_Current_User';
reg.openkey('ControlPanel/Desktop',false);
reg.WriteString('TitleWallpaper','0');
reg.writeString('Wallpaper',filelistbox1.filename);
reg.closereg;
reg.free;
◇[DELPHI]About keyboard constant names
VK_BACK/VK_TAB/VK_RETURN/VK_SHIFT/VK_CONTROL/VK_MENU/VK_PAUSE/VK_ESCAPE
/VK_SPACE/VK_LEFT/VK_RIGHT/VK_UP/VK_DOWN
F1--F12:$70(112)--$7B(123)
AZ:$41(65)--$5A(90)
0-9:$30(48)--$39(57)
◇[DELPHI] Preliminarily determine the native language of the program
DOS prompt of DELPHI software: ThisPRogramMustBeRunUnderWin32.
DOS prompt for VC++ software: ThisProgramCannotBeRunInDOSMode.
◇[DELPHI]Operating Cookies
response.cookies("name").domain:='http://www.086net.com';
withresponse.cookies.adddo
begin
name:='username';
value:='username';
end
◇[DELPHI] added to document menu link
usesshellapi,shlOBJ;
shAddToRecentDocs(shArd_path,pchar(filepath));//Add connection
shAddToRecentDocs(shArd_path,nil);//Clear
◇[Miscellaneous] Backup intelligent ABC input method dictionary
windows/system/user.rem
windows/system/tmmr.rem
◇[DELPHI] Determine mouse buttons
ifGetAsyncKeyState(VK_LButton)<>0then...//Left button
ifGetAsyncKeyState(VK_MButton)<>0then...//Middle key
ifGetAsyncKeyState(VK_RButton)<>0then...//Right click
◇[DELPHI]Set the maximum display of the form
onFormCreate event
self.width:=screen.width;
self.height:=screen.height;
◇[DELPHI] button to accept messages
Processed in the OnCreate event: application.OnMessage:=MyOnMessage;
procedureTForm1.MyOnMessage(varMSG:TMSG;varHandle:Boolean);
begin
ifmsg.message=256then...//ANY key
ifmsg.message=112then...//F1
ifmsg.message=113then...//F2
end;
◇[Miscellaneous]Hide shared folders
Sharing effect: accessible, but invisible (in resource management, Network Neighborhood)
Name the share: direction$
Visit ://computer/direction/
◇[javaScript]Commonly used effects on JavaScript web pages
The webpage is scheduled to close in 60 seconds
close window
closure
Scheduled URL transfer
It is also possible to configure TQuery during operation, see Delphi help for details.
□◇[DELPHI] Get the RGB value of a certain point on the image
procedureTForm1.Image1MouseDown(Sender:TObject;Button:TMouseButton;
Shift:TShiftState;X,Y:Integer);
var
red,green,blue:byte;
i:integer;
begin
i:=image1.Canvas.Pixels[x,y];
Blue:=GetBValue(i);
Green:=GetGValue(i):
Red:=GetRValue(i);
Label1.Caption:=inttostr(Red);
Label2.Caption:=inttostr(Green);
Label3.Caption:=inttostr(Blue);
end;
□◇[DELPHI]About date format decomposition and conversion
varyear,month,day:Word;now2:Tdatatime;
now2:=date();
decodedate(now2,year,month,day);
lable1.Text:=inttostr(year)+'year'+inttostr(month)+'month'+inttostr(day)+'day';
◇[DELPHI]How to determine the current network connection mode
The judgment result is MODEM, LAN or proxy server mode.
useswininet;
FunctionConnectionKind:boolean;
varflags:dword;
begin
Result:=InternetGetConnectedState(@flags,0);
ifResultthen
begin
if(flagsandINTERNET_CONNECTION_MODEM)=INTERNET_CONNECTION_MODEMthen
begin
showmessage('Modem');
end;
if(flagsandINTERNET_CONNECTION_LAN)=INTERNET_CONNECTION_LANthen
begin
showmessage('LAN');
end;
if(flagsandINTERNET_CONNECTION_PROXY)=INTERNET_CONNECTION_PROXYthen
begin
showmessage('Proxy');
end;
if(flagsandINTERNET_CONNECTION_MODEM_BUSY)=INTERNET_CONNECTION_MODEM_BUSYthen
begin
showmessage('ModemBusy');
end;
end;
end;
◇[DELPHI]How to determine whether a string is a valid EMAIL address
functionIsEMail(EMail:String):Boolean;
vars:String;ETpos:Integer;
begin
ETpos:=pos('@',EMail);
ifETpos>1then
begin
s:=copy(EMail,ETpos+1,Length(EMail));
if(pos('.',s)>1)and(pos('.',s)<length(s))then
Result:=trueelseResult:=false;
end
else
Result:=false;
end;
◇[DELPHI] Determine whether the system is connected to INTERNET
The InetIsOffline function in URL.DLL needs to be introduced.
The function declaration is:
functionInetIsOffline(Flag:Integer):Boolean;stdcall;external'URL.DLL';
Then you can call the function to determine whether the system is connected to the INTERNET
ifInetIsOffline(0)thenShowMessage('notconnected!')
elseShowMessage('connected!');
This function returns TRUE if the local system is not connected to the INTERNET.
Attached:
Most systems with IE or OFFICE97 have this DLL available for calling.
InetIsOffline
BOOLInetIsOffline(
DWORDdwFlags,
);
◇[DELPHI]Easily play and pause WAV files
usesmmsystem;
functionPlayWav(constFileName:string):Boolean;
begin
Result:=PlaySound(PChar(FileName),0,SND_ASYNC);
end;
procedureStopWav;
var
buffer:array[0..2]ofchar;
begin
buffer[0]:=#0;
PlaySound(Buffer,0,SND_PURGE);
end;
◇[DELPHI] Get machine BIOS information
withMemo1.Linesdo
begin
Add('MainBoardBiosName:'+^I+string(Pchar(Ptr($FE061))));
Add('MainBoardBiosCopyRight:'+^I+string(Pchar(Ptr($FE091))));
Add('MainBoardBiosDate:'+^I+string(Pchar(Ptr($FFFF5))));
Add('MainBoardBiosSerialNo:'+^I+string(Pchar(Ptr($FEC71))));
end;
◇[DELPHI] Download files from the Internet
usesUrlMon;
functionDownloadFile(Source,Dest:string):Boolean;
begin
try
Result:=UrlDownloadToFile(nil,PChar(source),PChar(Dest),0,nil)=0;
except
Result:=False;
end;
end;
ifDownloadFile('http://www.borland.com/delphi6.zip,'c:/kylix.zip')then
ShowMessage('Downloadsuccesful')
elseShowMessage('Downloadunsuccesful')
◇[DELPHI]Resolve server IP address
useswinsock
functionIPAddrToName(IPAddr:String):String;
var
SockAddrIn:TSockAddrIn;
HostEnt:PHostEnt;
WSAData:TWSAData;
begin
WSAStartup($101,WSAData);
SockAddrIn.sin_addr.s_addr:=inet_addr(PChar(IPAddr));
HostEnt:=gethostbyaddr(@SockAddrIn.sin_addr.S_addr,4,AF_INET);
ifHostEnt<>nilthenresult:=StrPas(Hostent^.h_name)elseresult:='';
end;
◇[DELPHI] Get the connection in the shortcut
functionExeFromLink(constlinkname:string):string;
var
FDir,
Name,
ExeName:PChar;
z:integer;
begin
ExeName:=StrAlloc(MAX_PATH);
FName:=StrAlloc(MAX_PATH);
FDir:=StrAlloc(MAX_PATH);
StrPCopy(FName,ExtractFileName(linkname));
StrPCopy(FDir,ExtractFilePath(linkname));
z:=FindExecutable(FName,FDir,ExeName);
ifz>32then
Result:=StrPas(ExeName)
else
Result:='';
StrDispose(FDir);
StrDispose(FName);
StrDispose(ExeName);
end;
◇[DELPHI]Control the automatic completion of TCombobox
{'Sorted'propertyoftheTComboboxtotrue}
varlastKey:Word;//global variable
//OnChange event of TCombobox
procedureTForm1.AutoCompleteChange(Sender:TObject);
var
SearchStr:string;
retVal:integer;
begin
SearchStr:=(SenderasTCombobox).Text;
iflastKey<>VK_BACKthen//backspace:VK_BACKor$08
begin
retVal:=(SenderasTCombobox).Perform(CB_FINDSTRING,-1,LongInt(PChar(SearchStr)));
ifretVal>CB_Errthen
begin
(SenderasTCombobox).ItemIndex:=retVal;
(SenderasTCombobox).SelStart:=Length(SearchStr);
(SenderasTCombobox).SelLength:=
(Length((SenderasTCombobox).Text)-Length(SearchStr));
end;//retVal>CB_Err
end;//lastKey<>VK_BACK
lastKey:=0;//resetlastKey
end;
//OnKeyDown event of TCombobox
procedureTForm1.AutoCompleteKeyDown(Sender:TObject;varKey:Word;
Shift:TShiftState);
begin
lastKey:=Key;
end;
◇[DELPHI]How to clear a directory
functionEmptyDirectory(TheDirectory:String;Recursive:Boolean):
Boolean;
var
SearchRec:TSearchRec;
Res:Integer;
begin
Result:=False;
TheDirectory:=NormalDir(TheDirectory);
Res:=FindFirst(TheDirectory+'*.*',faAnyFile,SearchRec);
try
whileRes=0do
begin
if(SearchRec.Name<>'.')and(SearchRec.Name<>'..')then
begin
if((SearchRec.AttrandfaDirectory)>0)andRecursive
thenbegin
EmptyDirectory(TheDirectory+SearchRec.Name,True);
RemoveDirectory(PChar(TheDirectory+SearchRec.Name));
end
elsebegin
DeleteFile(PChar(TheDirectory+SearchRec.Name))
end;
end;
Res:=FindNext(SearchRec);
end;
Result:=True;
finally
FindClose(SearchRec.FindHandle);
end;
end;
◇[DELPHI]How to calculate the size of a directory
functionGetDirectorySize(constADirectory:string):Integer;
var
Dir:TSearchRec;
Ret:integer;
Path:string;
begin
Result:=0;
Path:=ExtractFilePath(ADirectory);
Ret:=Sysutils.FindFirst(ADirectory,faAnyFile,Dir);
ifRet<>NO_ERRORthenexit;
try
whileret=NO_ERRORdo
begin
inc(Result,Dir.Size);
if(Dir.Attrin[faDirectory])and(Dir.Name[1]<>'.')then
Inc(Result,GetDirectorySize(Path+Dir.Name+'/*.*'));
Ret:=Sysutils.FindNext(Dir);
end;
finally
Sysutils.FindClose(Dir);
end;
end;
◇[DELPHI]How to add the installer to the Uninstall list
Operate the registry as follows:
1. Create a primary key under the HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall key with any name.
ExampleHKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall/MyUninstall
2. Key two string values under HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall/MyUnistall,
The names of these two string values are specific: DisplayName and UninstallString.
3. Assign the value of the string DisplayName to the name displayed in the "Delete Application List", such as 'AimingUninstallone';
Assign the string UninstallString to the executed deletion command, such as C:/WIN97/uninst.exe-f "C:/TestPro/aimTest.isu"
◇[DELPHI]Intercepted WM_QUERYENDsession shutdown message
type
TForm1=class(TForm)
procedureWMQueryEndSession(varMessage:TWWMQueryEndSession);messageWM_QUERYENDSESSION;
procedureCMEraseBkgnd(varMessage:TWMEraseBkgnd);MessageWM_ERASEBKGND;
private
{Privatedeclarations}
public
{Publicdeclarations}
end;
procedureTForm1.WMQueryEndSession(varMessage:TWMQueryEndSession);
begin
Showmessage('computerisabouttoshutdown');
end;
◇[DELPHI]Get online neighbors
proceduregetnethood();//NT is used as the server, and debugging passed on WIN98.
var
a,i:integer;
errcode:integer;
netres:array[0..1023]ofnetresource;
enumhandle:thandle;
enumentries:dword;
buffersize:dword;
s:string;
mylistitems:tlistitems;
mylistitem:tlistitem;
alldomain:tstrings;
begin//listcomputerisalistviewtolistallcomputers;controlcenterisaform.
alldomain:=tstringlist.Create;
withnetres[0]dobegin
dwscope:=RESOURCE_GLOBALNET;
dwtype:=RESOURCETYPE_ANY;
dwdisplaytype:=RESOURCEDISPLAYTYPE_DOMAIN;
dwusage:=RESOURCEUSAGE_CONTAINER;
lplocalname:=nil;
lpremotename:=nil;
lpcomment:=nil;
lpprovider:=nil;
end;//Get all domains
errcode:=wnetopenenum(RESOURCE_GLOBALNET,RESOURCETYPE_ANY,RESOURCEUSAGE_CONTAINER,@netres[0],enumhandle);
iferrcode=NO_ERRORthenbegin
enumentries:=1024;
buffersize:=sizeof(netres);
errcode:=wnetenumresource(enumhandle,enumentries,@netres[0],buffersize);
end;
a:=0;
mylistitems:=controlcenter.lstcomputer.Items;
mylistitems.Clear;
while(string(netres[a].lpprovider)<>'')and(errcode=NO_ERROR)do
begin
alldomain.Add(netres[a].lpremotename);
a:=a+1;
end;
wnetcloseenum(enumhandle);
//Get all computers
mylistitems:=controlcenter.lstcomputer.Items;
mylistitems.Clear;
fori:=0toalldomain.Count-1do
begin
withnetres[0]dobegin
dwscope:=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);
iferrcode=NO_ERRORthen
begin
EnumEntries:=1024;
BufferSize:=SizeOf(NetRes);
ErrCode:=WNetEnumResource(EnumHandle,EnumEntries,@NetRes[0],BufferSize);
end;
a:=0;
while(string(netres[a].lpprovider)<>'')and(errcode=NO_ERROR)do
begin
mylistitem:=mylistitems.Add;
mylistitem.ImageIndex:=0;
mylistitem.Caption:=uppercase(stringreplace(string(NetRes[a].lpremotename),'//','',[rfReplaceAll]));
a:=a+1;
end;
wnetcloseenum(enumhandle);
end;
end;
◇[DELPHI] Get the shared directory on a certain computer
proceduregetsharefolder(constcomputername:string);
var
errcode,a:integer;
netres:array[0..1023]ofnetresource;
enumhandle:thandle;
enumentries,buffersize:dword;
s:string;
mylistitems:tlistitems;
mylistitem:tlistitem;
mystrings:tstringlist;
begin
withnetres[0]dobegin
dwscope:=RESOURCE_GLOBALNET;
dwtype:=RESOURCETYPE_DISK;
dwdisplaytype:=RESOURCEDISPLAYTYPE_SHARE;
dwusage:=RESOURCEUSAGE_CONTAINER;
lplocalname:=nil;
lpremotename:=pchar(computername);
lpcomment:=nil;
lpprovider:=nil;
end;//Get the root node
errcode:=wnetopenenum(RESOURCE_GLOBALNET,RESOURCETYPE_DISK,RESOURCEUSAGE_CONTAINER,@netres[0],enumhandle);
iferrcode=NO_ERRORthen
begin
EnumEntries:=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)do
begin
withmylistitemsdo
begin
mylistitem:=add;
mylistitem.ImageIndex:=4;
mylistitem.Caption:=extractfilename(netres[a].lpremotename);
end;
a:=a+1;
end;
end;
◇[DELPHI] Get the hard drive serial number
varSerialNum:pdword;a,b:dword;Buffer:array[0..255]ofchar;
begin
ifGetVolumeInformation('c:/',Buffer,SizeOf(Buffer),SerialNum,a,b,nil,0)thenLabel1.Caption:=IntToStr(SerialNum^);
end;
◇[DELPHI]MEMO’s automatic page turning
ProcedureScrollMemo(Memo:TMemo;Direction:char);
begin
casedirectionof
'd':begin
SendMessage(Memo.Handle,{HWNDoftheMemoControl}
WM_VSCROLL,{WindowsMessage}
SB_PAGEDOWN,{ScrollCommand}
0){NotUsed}
end;
'u':begin
SendMessage(Memo.Handle,{HWNDoftheMemoControl}
WM_VSCROLL,{WindowsMessage}
SB_PAGEUP,{ScrollCommand}
0);{NotUsed}
end;
end;
end;
procedureTForm1.Button1Click(Sender:TObject);
begin
ScrollMemo(Memo1,'d');//Turn up the page
end;
procedureTForm1.Button1Click(Sender:TObject);
begin
ScrollMemo(Memo1,'u');//Turn down the page
end;
◇[DELPHI]Press enter to the next position in DBGrid (Tab key)
procedureTForm1.DBGrid1KeyPress(Sender:TObject;varKey:Char);
begin
ifKey=#13then
ifDBGrid1.Columns.Grid.SelectedIndex<DBGrid1.Columns.Count-1then
DBGrid1.Columns[DBGrid1.Columns.grid.SelectedIndex+1].Field.FocusControl
else
begin
Table1.next;
DBGrid1.Columns[0].field.FocusControl;
end;
end;
◇[DELPHI]How to install the control
Installation method:
1. For a single control, Component-->installcomponent..-->PAS or DCU file-->install
2. For control packages with *.dpk files, just click File-->open (select *.dpk in the drop-down list box)-->install.
3. For control packages with *.dpl files, InstallPackages-->Add-->dpl file name.
4. If the above Install button is invalid, try the Compile button.
5. If it is runtimelib, add it to runtimepackes under packages under option.
If it prompts that the file cannot be found during compilation, it is usually because the installation directory of the control is not in the Lib directory of Delphi. There are two ways to solve the problem:
1. Copy the original installation files into the Lib directory of delphi.
2. Or add the original code path of the control to the Delphi Lib directory in Tools-->EnvironmentOptions.
◇[DELPHI] Completely delete the directory (deltree)
procedureTForm1.DeleteDirectory(strDir:String);
var
sr:TSearchRec;
FileAttrs:Integer;
strfilename:string;
strPth: string;
begin
strpth:=Getcurrentdir();
FileAttrs:=faAnyFile;
ifFindFirst(strpth+'/'+strdir+'/*.*',FileAttrs,sr)=0then
begin
if(sr.AttrandFileAttrs)=sr.Attrthen
begin
strfilename:=sr.Name;
iffileexists(strpth+'/'+strdir+'/'+strfilename)then
deletefile(strpth+'/'+strdir+'/'+strfilename);
end;
whileFindNext(sr)=0do
begin
if(sr.AttrandFileAttrs)=sr.Attrthen
begin
strfilename:=sr.name;
iffileexists(strpth+'/'+strdir+'/'+strfilename)then
deletefile(strpth+'/'+strdir+'/'+strfilename);
end;
end;
FindClose(sr);
removedir(strpth+'/'+strdir);
end;
end;
◇[DELPHI] Obtain the row and column information of the current cursor of the TMemo control into Tpoint
1.functionReadCursorPos(SourceMemo:TMemo):TPoint;
varPoint:TPoint;
begin
point.y:=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);//Line length
◇[DELPHI]Read hard disk serial number
functionGetDiskSerial(DiskChar:Char):string;
var
SerialNum:pdword;
a,b:dword;
Buffer:array[0..255]ofchar;
begin
result:="";
ifGetVolumeInformation(PChar(diskchar+":/"),Buffer,SizeOf(Buffer),SerialNum,
a,b,nil,0)then
Result:=IntToStr(SerialNum^);
end;
◇[INTERNET]Common CSS comprehensive skills
1. P:first-letter{font-size:300%;float:left}//The first letter will be three times larger than the normal font.
2.
3. Embed a style sheet
4.
Arial//SPAN accepts STYLE, CLASS and ID attributes
DIV can contain paragraphs, titles, tables and even other parts
5.
6. //See 3 for definition. 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>|<percent>] Text decoration: text-decoration: [underline||overline||line-through||blink] Text-transform:[none|capitalize|uppercase|lowercase] Background color:background-color:[<color>|transparent] background-image:background-image:[ Line-height:[normal|<number>|<length>|<percent>] Border-style:[none|dotted|dashed|solid|double|groove|ridge|inset|outset] float:float:[left|right|none] 8. unit of length Relative units: em (em, the height of the font of the element) ex(x-height, the height of the letter "x") px (pixels, relative to screen resolution) Absolute length: in (inch, 1 inch = 2.54 centimeters) cm (centimeter, 1 centimeter = 10 millimeters) mm(meter) pt (point, 1 point = 1/72 inch) pc (Pa, 1 Pa = 12 points) ◇[DELPHI] Brief steps for making VCL 1. Create component attribute method events (Create library units, inherit as new types, add properties, methods, events, register components, create package files) 2.Message processing 3.Exception handling 4. Parts visible ◇[DELPHI] Loading of dynamic link library Static loading: procedurename;external'lib.dll'; Dynamic loading:varhandle:Thandle; handle:=loadlibrary('lib.dll'); ifhandle<>0then begin {dosomething} freelibrary(handle); end; ◇[DELPHI]Pointer variables and addresses varx,y:integer;p:^integer;//Pointer to INTEGER variable x:=10; //Variable assignment p:=@x;//The address of variable x y:=p^;//Assign pointer P to Y @@procedure//Returns the memory address of the process variable ◇[DELPHI] determines whether the character is a Chinese character ByteType('How are you haha',1)=mbLeadByte//is the first character ByteType('How are you haha',2)=mbTrailByte//is the second character ByteType('How are you haha',5)=mbSingleByte//Not a Chinese character ◇[DELPHI]memo positioning operation memo1.lines.delete(0)//Delete line 1 memo1.selstart:=10//Locate 10 bytes ◇[DELPHI] Obtain double-byte character internal code functiongetit(s:string):integer; begin Result:=byte(s[1])*$100+byte(s[2]); end; Use: getit('calculation')//$bcc6 is decimal 48326 ◇[DELPHI]Call ADD data storage procedure The stored procedure is as follows: createprocedureaddrecord( record1varchar(10) record2varchar(20) ) as begin insertintotablename(field1,field2)values(:record1,:record2) end Execute stored procedure: EXECUTEprocedureaddrecord("urrecord1","urrecord2") ◇[DELPHI]Save files into blob fields functionblobcontenttostring(constfilename:string):string; begin withtfilestream.create(filename,fmopenread)do try setlength(Result,size); read(Pointer(Result)^,size); finally free; end; end; //save field begin if(opendialog1.execute)then begin sFileName:=OpenDialog1.FileName; adotable1.edit; adotable1.fieldbyname('visio').asstring:=Blobcontenttostring(FileName); adotable1.post; end; ◇[DELPHI]Copy all files to the clipboard usesshlobj,activex,clipbrd; procedureTform1.copytoclipbrd(varFileName:string); var FE:TFormatEtc; Medium:TStgMedium; dropfiles:PDropFiles; pFile:PChar; begin FE.cfFormat:=CF_HDROP; FE.dwaspect:=DVASPECT_CONTENT; FE.tymed:=TYMED_HGLOBAL; Medium.hGlobal:=GlobalAlloc(GMEM_SHAREorGMEM_ZEROINIT,SizeOf(TDropFiles)+length(FileName)+1); ifMedium.hGlobal<>0thenbegin Medium.tymed:=TYMED_HGLOBAL; dropfiles:=GlobalLock(Medium.hGlobal); try dropfiles^.pfiles:=SizeOf(TDropFiles); dropfiles^.fwide:=False; longint(pFile):=longint(dropfiles)+SizeOf(TDropFiles); StrPCopy(pFile,FileName); Inc(pFile,Length(FileName)+1); pFile^:=#0; finally GlobalUnlock(Medium.hGlobal); end; Clipboard.SetAsHandle(CF_HDROP,Medium.hGlobal); end; end; ◇[DELPHI] List the current system running processes usesTLHelp32; procedureTForm1.Button1Click(Sender:TObject); varlppe:TProcessEntry32; found:boolean; Hand:THandle; begin Hand:=CreateToolhelp32Snapshot(TH32CS_SNAPALL,0); found:=Process32First(Hand,lppe); whilefounddo begin ListBox1.Items.Add(StrPas(lppe.szExeFile)); found:=Process32Next(Hand,lppe); end; end; ◇[DELPHI]Create a new table Table2 based on BDETable1 Table2:=TTable.Create(nil); try Table2.DatabaseName:=Table1.DatabaseName; Table2.FieldDefs.Assign(Table1.FieldDefs); Table2.IndexDefs.Assign(Table1.IndexDefs); Table2.TableName:='new_table'; Table2.CreateTable(); finally Table2.Free(); end; ◇[DELPHI] The best way to understand DLL creation and reference //Look at DLLsource(FILE-->NEW-->DLL) first libraryproject1; uses SysUtils,Classes; functionaddit(f:integer;s:integer):integer;export; begin makeasum:=f+s; end; exports addit; end. //Call (INurPROJECT) implementation functionaddit(f:integer;s:integer):integer;far;external'project1';//Declaration {The call is addit(2,4); the result shows 6} ◇[DELPHI] Dynamically read the size of the program itself functionGesSelfSize:integer; var f:fileofbyte; begin filemode:=0; assignfile(f,application.exename); reset(f); Result:=filesize(f);//The unit is bytes closefile(f); end; ◇[DELPHI]Read BIOS information withMemo1.Linesdo begin Add('MainBoardBiosName:'+^I+string(Pchar(Ptr($FE061)))); Add('MainBoardBiosCopyRight:'+^I+string(Pchar(Ptr($FE091)))); Add('MainBoardBiosDate:'+^I+string(Pchar(Ptr($FFFF5)))); Add('MainBoardBiosSerialNo:'+^I+string(Pchar(Ptr($FEC71)))); end; ◇[DELPHI]Dynamicly create MSSQL aliases procedureTForm1.Button1Click(Sender:TObject); varMyList:TStringList; begin MyList:=TStringList.Create; try withMyListdo begin Add('SERVERNAME=210.242.86.2'); Add('DATABASENAME=db'); Add('USERNAME=sa'); end; Session1.AddAlias('TESTSQL','MSSQL',MyList);//ミMSSQL Session1.SaveConfigFile; finally MyList.Free; Session1.Active:=True; Database1.DatabaseName:='DB'; Database1.AliasName:='TESTSQL'; Database1.LoginPrompt:=False; Database1.Params.Add('USERNAME=sa'); Database1.Params.Add('PASSWORD='); Database1.Connected:=True; end; end; procedureTForm1.Button2Click(Sender:TObject); begin Database1.Connected:=False; Session1.DeleteAlias('TESTSQL'); end; ◇[DELPHI] Play background music usesmmsystem //Play music MCISendString('OPENe:/1.MIDTYPESEQUENCERALIASNN','',0,0); MCISendString('PLAYNNFROM0','',0,0); MCISendString('CLOSEANIMATION','',0,0); end; //Stop playing MCISendString('OPENe:/1.MIDTYPESEQUENCERALIASNN','',0,0); MCISendString('STOPNN','',0,0); MCISendString('CLOSEANIMATION','',0,0); ◇[DELPHI]A sample code for interfaces and classes Type{Interface and class declaration: The difference is that data members, any non-public methods, and public methods do not use the PUBLIC keyword in the interface} Isample=interface//Define Isample interface functiongetstring:string; end; Tsample=class(TInterfacedObject,Isample) public functiongetstring:string; end; //function definition functionTsample.getstring:string; begin result:='whatshowis'; end; //Call class object varsample:Tsample; begin sample:=Tsample.create; showmessage(sample.getstring+'classobject!'); sample.free; end; //Call interface varsampleinterface:Isample; sample:Tsample; begin sample:=Tsample.create; sampleInterface:=sample;//The implementation of Interface must use class {The above two lines can also be expressed as sampleInterface:=Tsample.create;} showmessage(sampleInterface.getstring+'Interface!'); //sample.free;{Unlike local classes, classes in Interface are automatically released} sampleInterface:=nil;{release interface object} end; ◇[DELPHI] The task bar does not look like an appropriate program var ExtendedStyle:Integer; begin Application.Initialize; ExtendedStyle:=GetWindowLong(Application.Handle,GWL_EXSTYLE); SetWindowLong(Application.Handle,GWL_EXSTYLE,ExtendedStyleORWS_EX_TOOLWINDOWANDNOTWS_EX_APPWINDOW); Application.CreateForm(TForm1,Form1); Application.Run; end. ◇[DELPHI]ALT+CTRL+DEL cannot see the program Add declaration after implementation: functionRegisterServiceProcess(dwProcessID,dwType:Integer):Integer;stdcall;external'KERNEL32.DLL'; RegisterServiceProcess(GetCurrentProcessID,1);//Hide RegisterServiceProcess(GetCurrentProcessID,0);//Display ◇[DELPHI]Detect optical drive symbol vardrive:char; cdromID:integer; begin fordrive:='d'to'z'do begin cdromID:=GetDriveType(pchar(drive+':/')); ifcdromID=5thenshowmessage('Your CD-ROM drive is:'+drive+'disk!'); end; end; ◇[DELPHI] detect sound card ifauxGetNumDevs()<=0thenshowmessage('Nosoundcardfound!')elseshowmessage('Anysoundcardfound!'); ◇[DELPHI]Draw in the string grid StringGrid.OnDrawCell event withStringGrid1.Canvasdo Draw(Rect.Left,Rect.Top,Image1.Picture.Graphic); ◇[SQLSERVER]Another way to write the Like statement in SQL For example, to find all users whose username contains "c", you can use usemydatabase select*fromtable1whereusernamelike'%c%" Here is another way to complete the above function: usemydatabase select*fromtable1wherecharindex('c',username)>0 In theory, this method has one more judgment statement than the previous method, that is, >0, but this judgment process is the fastest. I believe that more than 80% of the operations are spent on searching for words. For string and other operations, it is not a big deal to use the charindex function. There are also advantages to using this method, that is, you cannot directly use like for %, |, etc. The found characters can be used directly in this charindex, as follows: usemydatabase select*fromtable1wherecharindex('%',username)>0 It can also be written as: usemydatabase select*fromtable1wherecharindex(char(37),username)>0 The ASCII character is % ◇[DELPHI]SQL displays multiple databases/tables SELECTDISTINCTA.bianhao,a.xingming,b.gongziFROM"jianjie.dbf"a,"gongzi.DBF"b WHEREA.bianhao=b.bianhao ◇[DELPHI]RFC (RequestForComment) related IETF (Internet Engineering Task Force) maintains RFC documents http://www.ietf.cnri.reston.va.us RFC882: Message header structure RFC1521: MIME Part 1, Transmission Message Method RFC1945: Multimedia Document Transfer Documentation ◇[DELPHI]Usage of TNMUUPProcessor varinStream,outStream:TFileStream; begin inStream:=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 processing} //NMUUE.Decode;{decoding processing} inStream.free; outStream.free; end; ◇[DELPHI]TFileStream operation //Read count bytes from the current position of the file stream to the buffer BUFFER functionread(varbuffer;count:longint):longint;override; //Read the buffer BUFFER into the file stream functionwrite(constbuffer;count:longint):longint;override; //Set the current read and write pointer of the file stream to OFFSET functionseek(offset:longint;origin:word):longint;override; origin={soFromBeginning,soFromCurrent,soFromEnd} //Copy COUNT from the current position in another file stream to the current position in the current file stream functioncopyfrom(source:TStream;count:longint):longint; //Read the specified file to the file stream varmyFStream:TFileStream; begin myFStream:=TFileStream.create(OpenDialog1.filename,fmOpenRead); end; [Javascript] Check whether IE plug-in Shockwave&Quicktime is installed ------------------ Thank you for your patience in reading, you have a skill, I hope you will continue to post it!