The basic development skills of DELPHI from our ancestors
Compilation: Tenants Source: Monopoly Forum
◇[DELPHI] Copy files from Network Neighborhood
uses shellapi;
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:
var xpanel,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
uses shellapi;
var windir:array[0..255] of char;
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
var x,y:array [0..50] of integer;
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
var tips:tstringlist;
tips:=tstringlist.create;
tips.loadfromfile('filename.txt');
edit1.text:=tips[0];
tips.add('last line addition string');
tips.insert(1,'insert string at NO 2 line');
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 (attr and faReadonly)=faReadonly then ... //read only
if (attr and faSysfile)=faSysfile then ... //system
if (attr and faArchive)=faArchive then ... //Archive
if (attr and faHidden)=faHidden then ... //Hide
◇[DELPHI]Execute files outside the program
WINEXEC//Call executable file
winexec('command.com /c copy *.* c:/',SW_Normal);
winexec('start abc.txt');
ShellExecute or ShellExecuteEx//Start the file association 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:[email protected]','','',0);
◇[DELPHI] Get the name of the process running on the system
var hCurrentWindow:HWnd;szText:array[0..254] of char;
begin
hCurrentWindow:=Getwindow(handle,GW_HWndFrist);
while hCurrentWindow <> 0 do
begin
if Getwindowtext(hcurrnetwindow,@sztext,255)>0 then listbox1.items.add(strpas(@sztext));
hCurrentWindow:=Getwindow(hCurrentwindow,GW_HWndNext);
end;
end;
◇[DELPHI]About embedding of assembly
Asm End;
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 excess characters will be truncated. If Pos is outside 255, a runtime error will occur. For example, st:='Brian', then Insert('OK',st,2) will make st become '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 numeric value and conform to the rules for numeric 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 'Brian Wilfred'.
Length(st);//Returns the length of the string expression st. For example, st:='Brian', 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:='Brian Wilfred', 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
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]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: This PRogram Must Be Run Under Win32.
DOS prompt for VC++ software: This Program Cannot Be Run In DOS Mode.
◇[DELPHI]Operating Cookies
response.cookies("name").domain:='http://www.086net.com';
with response.cookies.add do
begin
name:='username';
value:='username';
end
◇[DELPHI] added to document menu link
uses shellapi,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
if GetAsyncKeyState(VK_LButton)<>0 then ... //Left button
if GetAsyncKeyState(VK_MButton)<>0 then ... //middle key
if GetAsyncKeyState(VK_RButton)<>0 then ... //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;
procedure TForm1.MyOnMessage(var MSG:TMSG;var Handle:Boolean);
begin
if msg.message=256 then ... //ANY key
if msg.message=112 then ... //F1
if msg.message=113 then ... //F2
end;
◇[Miscellaneous]Hide shared folders
Sharing effect: accessible, but invisible (in resource management, Network Neighborhood)
Name the share: direction$
Visit: //computer/direction/
◇[java Script] Commonly used effects on Java Script web pages
The webpage is scheduled to close in 60 seconds
<script language="java script"><!--
settimeout('window.close();',60000)
--></script>
close window
<a href="/" onclick="Javascript:window.close();return false;">Close</a>
Scheduled URL transfer
<meta http-equiv="refresh" content="40;url=http://www.086net.com">
Set as homepage
<a onclick="this.style.behavior='url(#default#homepage)';this.sethomepage('http://086net.com');"href="#">Set as homepage</a>
Bookmark this site
<a href="javascript:window.external.addfavorite('http://086net.com','[无名pier]')">Favorite this site</a>
Join channel
<a href="javascript:window.external.addchannel('http://086net.com')">Add channel</a>
◇[DELPHI]Text editing related
checkbox1.checked:=not checkbox1.checked;
if checkbox1.checked then richedit1.font.style:=richedit1.font.style+[fsBold] else richedit1.font.style:=richedit1.font.style-[fsBold]//bold
if checkbox1.checked then richedit1.font.style:=richedit1.font.style+[fsItalic] else richedit1.font.style:=richedit1.font.style-[fsItalic]//italic
if checkbox1.checked then richedit1.font.style:=richedit1.font.style+[fsUnderline] else richedit1.font.style:=richedit1.font.style-[fsUnderline]//underline
memo1.alignment:=taLeftJustify;//Left
memo1.alignment:=taRightJustify;//right
memo1.alignment:=taCenter;//Centered
◇[DELPHI] Randomly generate text color
randomize;//random seed
memo1.font.color:=rgb(random(255),random(255),random(255));
◇[DELPHI]DELPHI5 UPDATE upgrade patch serial number
1000003185
90X25fx0
◇[DELPHI] Illegal character filtering in file names
for i:=1 to length(s) do
if s[i] in ['/','/',':','*','?','<','>','|'] then
◇[DELPHI]Definition and description of conversion function
datetimetofiledate (datetime:Tdatetime):longint; Converts a date and time value in Tdatetime format to a date and time value in DOS format
datetimetostr (datetime:Tdatetime):string; Convert the Tdatatime format variable into a string. If the datetime parameter does not contain a date value, the returned string date will be displayed as 00/00/00. If there is no time value in the datetime parameter, the returned string will be The time portion displays as 00:00:00 AM
datetimetostring (var result string;
const format:string;
datetime:Tdatetime); Convert time and date values according to the given format string, result is the result string, format is the conversion format string, datetime is the date and time value
datetostr (date:Tdatetime) uses the format string defined by the shortdateformat global variable to convert the date parameter into the corresponding string
floattodecimal (var result:Tfloatrec;value:
extended;precision,decimals:
integer); Convert floating point number to decimal representation
floattostr (value:extended):string Converts the floating point value into string format. This conversion uses ordinary number format, and the effective number of digits converted is 15.
floattotext (buffer:pchar;value:extended;
format:Tfloatformat;precision,
digits:integer):integer; Use the given format, precision and decimal to convert the floating point value value into decimal representation. The conversion result is stored in the buffer parameter. The function return value is the number of characters stored in the buffer. The buffer is not 0 result string buffer.
floattotextfmt (buffer:pchar;value:extended;
format:pchar):integer Use the given format to convert the floating point value value into decimal representation. The conversion result is stored in the buffer parameter. The function return value is the number of characters stored in the buffer.
inttohex (value:longint;digits:integer):
string; Converts the given numerical value into a hexadecimal string. The parameter digits gives the number of digits contained in the conversion result string.
inttostr (value:longint):string converts an integer into a decimal string
strtodate (const S:string):Tdatetime Converts a string into a date value. S must contain a legal format date string.
strtodatetime (const S:string):Tdatetime Converts string S into date time format, S must have MM/DD/YY HH:MM:SS[AM|PM] format, where the date and time separators are the same as the system period time constant Setting related. If no AM or PM information is specified, the 24-hour clock is used.
strtofloat (const S:string):extended; Convert the given string into a floating point number. The string has the following format:
[+|-]nnn…[.]nnn…[<+|-><E|e><+|->nnnn]
strtoint (const S:string):longint Converts a numeric string into an integer. The string can be in decimal or hexadecimal format. If the string is not a legal numeric string, the system will generate an ECONVERTERROR exception.
strtointdef (const S:string;default:
longint):longint; Convert the string S into a number. If S cannot be converted into a number, the strtointdef function returns the value of the parameter default.
strtotime (const S:string):Tdatetime Converts the string S into a TDATETIME value. S has the format HH:MM:SS[AM|PM]. The actual format is related to the time-related global variables of the system.
timetostr (time:Tdatetime):string; Convert parameter TIME into a string. The format of the conversion result string is related to the setting of the system's time-related constants.
◇[DELPHI] program does not appear in ALT+CTRL+DEL
Add declaration after implementation:
function RegisterServiceProcess(dwProcessID, dwType: Integer): Integer; stdcall; external 'KERNEL32.DLL';
RegisterServiceProcess(GetCurrentProcessID, 1);//Hide
RegisterServiceProcess(GetCurrentProcessID, 0);//Display
Invisible with ALT+DEL+CTRL
◇[DELPHI] program does not appear in the taskbar
uses windows
var
ExtendedStyle : Integer;
begin
Application.Initialize;
//================================================ ==============
ExtendedStyle := GetWindowLong (Application.Handle, GWL_EXSTYLE);
SetWindowLong(Application.Handle, GWL_EXSTYLE, ExtendedStyle OR WS_EX_TOOLWINDOW
AND NOT WS_EX_APPWINDOW);
//================================================ ===============
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
◇[DELPHI]How to determine whether dial-up network is on or off
if GetSystemMetrics(SM_NETWORK) AND $01 = $01 then
showmessage('Online!')
else showmessage('Not online!');
◇[DELPHI]Convert IP to domain name
function GetDomainName(Ip:string):string;
var
pH:PHostent;
data:twsadata;
ii:dWord;
begin
WSAStartup($101, Data);
ii:=inet_addr(pchar(ip));
pH:=gethostbyaddr(@ii,sizeof(ii),PF_INET);
if (ph<>nil) then
result:=pH.h_name
else
result:='';
WSACleanup;
end;
◇[DELPHI] How to deal with "right-click menu"
var
reg: TRegistry;
begin
reg := TRegistry.Create;
reg.RootKey:=HKEY_CLASSES_ROOT;
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]Send virtual key value ctrl V
procedure sendpaste;
begin
keybd_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);
end;
◇[DELPHI]The drive letter of the current optical drive
procedure getcdrom(var cd:char);
var
str:string;
drivers:integer;
driver:char;
i,temp:integer;
begin
drivers:=getlogicaldrives;
temp:=(1 and drivers);
for i:=0 to 26 do
begin
if temp=1 then
begin
driver:=char(i+integer('a'));
str:=driver+':';
if getdrivetype(pchar(str))=drive_cdrom then
begin
cd:=driver;
exit;
end;
end;
drivers:=(drivers shr 1);
temp:=(1 and drivers);
end;
end;
◇[DELPHI]Encryption and decryption of characters
function cryptstr(const s:string; stype: dword):string;
var
i: integer;
fkey: integer;
begin
result:='';
case type of
0: setpass;
begin
randomize;
fkey := random($ff);
for i:=1 to length(s) do
result := result+chr( ord(s[i]) xor i xor fkey);
result := result + char(fkey);
end;
1:getpass
begin
fkey := ord(s[length(s)]);
for i:=1 to length(s) - 1 do
result := result+chr( ord(s[i]) xor i xor fkey);
end;
end;
□◇[DELPHI] Send simulated keys to other applications
var
h:THandle;
begin
h := FindWindow(nil, 'Application title');
PostMessage(h, WM_KEYDOWN, VK_F9, 0);//Send F9 key
end;
□◇[DELPHI] DAO data format supported by DELPHI
td.Fields.Append(td.CreateField ('dbBoolean',dbBoolean,0));
td.Fields.Append(td.CreateField ('dbByte',dbByte,0));
td.Fields.Append(td.CreateField ('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 ('dbBinary',dbBinary,0));
td.Fields.Append(td.CreateField ('dbText',dbText,0));
td.Fields.Append(td.CreateField ('dbLongBinary',dbLongBinary,0));
td.Fields.Append(td.CreateField ('dbMemo',dbMemo,0));
td.Fields['ID'].Set_Attributes(dbAutoIncrField);//Auto-increment field
□◇[DELPHI]DELPHI configure MS SQL 7 and BDE steps
The first step is to configure ODBC:
First set up the data source in ODBC. After installing SQL Server7.0, there should be two items in "System DSN" in ODBC.
Data sources, one is MQIS and the other is LocalSever. Select any one and click the configure button. I don’t know your SQL7.0
Is it installed on the local machine? If so, proceed directly to the next step. If not, fill in the server column.
Server, then proceed to the next step and fill in the login ID and password (the login ID and password are user options in SQL7.0
centrally located).
The second step is to configure BDE:
Open Delphi's BDE and click MQIS or LocalServer. You will be prompted for a username and password. This is the same as
The ODBC username and password are the same, just fill them in.
The third step is to configure the program:
If you are using TTable, select MQIS or LocalServer in the DatabaseName of TTable, and then
Just select Sale in TableName, then change Active to True. Delphi will pop up a prompt dialog and fill in the user
name and password.
If you are using TQuery, right-click on TQuery and click "SQL Builder". This is configured in interface mode.
SQL statement, or fill in the SQL statement in TQuery's SQL. Finally, don’t forget to change Active to True.
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
procedure TForm1.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
var year,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.
uses wininet;
Function ConnectionKind :boolean;
var flags: dword;
begin
Result := InternetGetConnectedState(@flags, 0);
if Result then
begin
if (flags and INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM then
begin
showmessage('Modem');
end;
if (flags and INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN then
begin
showmessage('LAN');
end;
if (flags and INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY then
begin
showmessage('Proxy');
end;
if (flags and INTERNET_CONNECTION_MODEM_BUSY)=INTERNET_CONNECTION_MODEM_BUSY then
begin
showmessage('Modem Busy');
end;
end;
end;
◇[DELPHI]How to determine whether a string is a valid EMAIL address
function IsEMail(EMail: String): Boolean;
var s: String;ETpos: Integer;
begin
ETpos:= pos('@', EMail);
if ETpos > 1 then
begin
s:= copy(EMail,ETpos+1,Length(EMail));
if (pos('.', s) > 1) and (pos('.', s) < length(s)) then
Result:= true else Result:= 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:
function InetIsOffline(Flag: Integer): Boolean; stdcall; external 'URL.DLL';
Then you can call the function to determine whether the system is connected to the INTERNET
if InetIsOffline(0) then ShowMessage('not connected!')
else ShowMessage('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
BOOL InetIsOffline(
DWORD dwFlags,
);
◇[DELPHI]Easily play and pause WAV files
uses mmsystem;
function PlayWav(const FileName: string): Boolean;
begin
Result := PlaySound(PChar(FileName), 0, SND_ASYNC);
end;
procedure StopWav;
var
buffer: array[0..2] of char;
begin
buffer[0] := #0;
PlaySound(Buffer, 0, SND_PURGE);
end;
◇[DELPHI] Get machine BIOS information
with Memo1.Lines do
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
uses UrlMon;
function DownloadFile(Source, Dest: string): Boolean;
begin
try
Result := UrlDownloadToFile(nil, PChar(source), PChar(Dest), 0, nil) = 0;
except
Result := False;
end;
end;
if DownloadFile('http://www.borland.com/delphi6.zip, 'c:/kylix.zip') then
ShowMessage('Download succesful')
else ShowMessage('Download unsuccesful')
◇[DELPHI]Resolve server IP address
uses winsock
function IPAddrToName(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);
if HostEnt<>nil then result:=StrPas(Hostent^.h_name) else result:='';
end;
◇[DELPHI] Get the connection in the shortcut
function ExeFromLink(const linkname: 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);
if z > 32 then
Result:= StrPas(ExeName)
else
Result:= '';
StrDispose(FDir);
StrDispose(FName);
StrDispose(ExeName);
end;
◇[DELPHI]Control the automatic completion of TCombobox
{'Sorted' property of the TCombobox to true }
var lastKey: Word; //global variable
//OnChange event of TCombobox
procedure TForm1.AutoCompleteChange(Sender: TObject);
var
SearchStr: string;
retVal: integer;
begin
SearchStr := (Sender as TCombobox).Text;
if lastKey <> VK_BACK then // backspace: VK_BACK or $08
begin
retVal := (Sender as TCombobox).Perform(CB_FINDSTRING, -1, LongInt(PChar(SearchStr)));
if retVal > CB_Err then
begin
(Sender as TCombobox).ItemIndex := retVal;
(Sender as TCombobox).SelStart := Length(SearchStr);
(Sender as TCombobox).SelLength :=
(Length((Sender as TCombobox).Text) - Length(SearchStr));
end; // retVal > CB_Err
end; // lastKey <> VK_BACK
lastKey := 0; // reset lastKey
end;
//OnKeyDown event of TCombobox
procedure TForm1.AutoCompleteKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
lastKey := Key;
end;
◇[DELPHI]How to clear a directory
function EmptyDirectory(TheDirectory :String ; Recursive : Boolean) :
Boolean;
var
SearchRec : TSearchRec;
Res : Integer;
begin
Result := False;
TheDirectory := NormalDir(TheDirectory);
Res := FindFirst(TheDirectory + '*.*', faAnyFile, SearchRec);
try
while Res = 0 do
begin
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then
begin
if ((SearchRec.Attr and faDirectory) > 0) and Recursive
then begin
EmptyDirectory(TheDirectory + SearchRec.Name, True);
RemoveDirectory(PChar(TheDirectory + SearchRec.Name));
end
else begin
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
function GetDirectorySize(const ADirectory: string): Integer;
var
Dir: TSearchRec;
Ret: integer;
Path: string;
begin
Result := 0;
Path := ExtractFilePath(ADirectory);
Ret := Sysutils.FindFirst(ADirectory, faAnyFile, Dir);
if Ret <> NO_ERROR then exit;
try
while ret=NO_ERROR do
begin
inc(Result, Dir.Size);
if (Dir.Attr in [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 'Aiming Uninstall one';
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)
procedure WMQueryEndSession(var Message: TWMQueryEndSession); message WM_QUERYENDSESSION;
procedure CMEraseBkgnd(var Message:TWMEraseBkgnd);Message WM_ERASEBKGND;
private
{Private declarations}
public
{Public declarations}
end;
procedure TForm1.WMQueryEndSession(var Message: TWMQueryEndSession);
begin
Showmessage('computer is about to shut down');
end;
◇[DELPHI]Get online neighbors
procedure getnethood();//NT is used as the server, and debugging passed on WIN98.
var
a,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 begin
dwscope :=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 begin
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;
for i:=0 to alldomain.Count-1 do
begin
with netres[0] do begin
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);
if errcode=NO_ERROR then
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
procedure getsharefolder(const computername:string);
var
errcode,a:integer;
netres:array[0..1023] of netresource;
enumhandle:thandle;
enumentries,buffersize:dword;
s:string;
mylistitems:tlistitems;
mylistitem:tlistitem;
mystrings:tstringlist;
begin
with netres[0] do begin
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);
if errcode=NO_ERROR then
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
with mylistitems do
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
var SerialNum : pdword; a, b : dword; Buffer : array [0..255] of char;
begin
if GetVolumeInformation('c:/', Buffer, SizeOf(Buffer), SerialNum, a, b, nil, 0) then Label1.Caption := IntToStr(SerialNum^);
end;
◇[DELPHI]MEMO’s automatic page turning
Procedure ScrollMemo(Memo: TMemo; Direction: char);
begin
case direction of
'd': begin
SendMessage(Memo.Handle, { HWND of the Memo Control }
WM_VSCROLL, { Windows Message }
SB_PAGEDOWN, { Scroll Command }
0) { Not Used }
end;
'u' : begin
SendMessage(Memo.Handle, { HWND of the Memo Control }
WM_VSCROLL, { Windows Message }
SB_PAGEUP, { Scroll Command }
0); { Not Used }
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ScrollMemo(Memo1,'d'); //page up
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
ScrollMemo(Memo1,'u'); //Turn down the page
end;
◇[DELPHI]Press enter to the next position in DBGrid (Tab key)
procedure TForm1.DBGrid1KeyPress(Sender: TObject; var Key: Char);
begin
if Key = #13 then
if DBGrid1.Columns.Grid.SelectedIndex < DBGrid1.Columns.Count - 1 then
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-->install component..-->PAS or DCU file-->install
2. For control packages with *.dpk files, File-->open (select *.dpk in the drop-down list box)-->install.
3. For control packages with *.dpl files, Install Packages-->Add-->dpl file name.
4. If the above Install button is invalid, try the Compile button.
5. If it is run time lib, 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 methods 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-->Environment Options.
◇[DELPHI] Completely delete the directory (deltree)
procedure TForm1.DeleteDirectory(strDir:String);
var
sr: TSearchRec;
FileAttrs: Integer;
strfilename:string;
strPth: string;
begin
strpth:=Getcurrentdir();
FileAttrs := faAnyFile;
if FindFirst(strpth+'/'+strdir+'/*.*', FileAttrs, sr) = 0 then
begin
if (sr.Attr and FileAttrs) = sr.Attr then
begin
strfilename:=sr.Name;
if fileexists(strpth+'/'+strdir+'/'+strfilename) then
deletefile(strpth+'/'+strdir+'/'+strfilename);
end;
while FindNext(sr) = 0 do
begin
if (sr.Attr and FileAttrs) = sr.Attr then
begin
strfilename:=sr.name;
if fileexists(strpth+'/'+strdir+'/'+strfilename) then
deletefile(strpth+'/'+strdir+'/'+strfilename);
end;
end;
FindClose(sr);
removedir(strpth+'/'+strdir);
end;
end;
◇[DELPHI] Obtain the row and column information of the current cursor of the TMemo control into Tpoint
1.function ReadCursorPos(SourceMemo: TMemo): TPoint;
var Point: 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
function GetDiskSerial(DiskChar: Char): string;
var
SerialNum : pdword;
a, b : dword;
Buffer: array [0..255] of char;
begin
result := "";
if GetVolumeInformation(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. <LINK REL=StyleSheet HREF="basics.css" TITLE="Contemporary">//Connect an external style sheet
3. Embed a style sheet
<STYLE TYPE="text/css" MEDIA=screen>
<!--
@import url(http://www.htmlhelp.com/style.css);//Externally import a style sheet
@import url(/stylesheets/punk.css);//Same as above
BODY { background: url(foo.gif) red; color: black }
.punk { color: lime; background: #ff80c0 }//See 5 for reference.
#wdg97 { font-size: larger }//See 6 for references.
-->
</STYLE>
4. <P STYLE="color: red; font-family: 'New Century Schoolbook', serif"> //Inline style
<SPAN STYLE="font-family: Arial">Arial</SPAN>//SPAN accepts STYLE, CLASS and ID attributes
<DIV CLASS=note><P>DIV can contain paragraphs, titles, tables and even other parts</P></DIV>
5. <H1 CLASS=punk>CLASS attribute</H1>//See 3 for definition.
6. <P ID=wdg97>ID attribute</P>//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 transformation: text-transform:[none | capitalize | uppercase | lowercase]
Background color: background-color:[<color> | transparent]
Background image: background-image:[<URLs> | none]
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 element's font)
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, and create package files)
2.Message processing
3.Exception handling
4. Parts visible
◇[DELPHI] Loading of dynamic link library
Static loading: procedure name;external 'lib.dll';
Dynamic loading: var handle:Thandle;
handle:=loadlibrary('lib.dll');
if handle <> 0 then
begin
{Dosomething}
freelibrary (handle);
end;
◇ [Delphi] poem variable and address
var x, y: integer; p:^integer; // pointer pointer to Integer variable
x: = 10; // Value of variables
p: =@x; // The address of the variable x
y: = p^; // Assignment pointer P for Y
@@ Procedure // The memory address of the variable of the process variable
◇ [Delphi] Judging the character is a character of Chinese characters
Bytetype ('Hello haha ", 1) = mbleadbyte // is the first character
Bytetype ('Hello haha', 2) = mbtrailbyte // is the second character
Bytetype ('Hello haha ", 5) = mbsinglebyte // Not a Chinese character
◇ [Delphi] Memo's positioning operation
memo1.lines.delete (0) // Delete line 1
Memo1.Selstart: = 10 // Positioning 10 bytes
◇ [Delphi] Get dual -byte character internal code
function getit (s: string): Integer;
begin
Result: = byte (s [1]) * $ 100 + byte (s [2]);
end;
Use: getitit ('plan') // $ BCC6 is the decimal 48326
◇ [Delphi] Call the ADD data storage procedure
The storage procedure is as follows:
Create Procedure Addrecord (
Record1 varchar (10)
Record2 varchar (20)
)
as
begin
Insert Into Tablename (Field1, Field2) Values (: Record1,: Record2)
end
Execute the storage procedure:
Execute Procedure AdDRecord ("Urrecord1", "Urrecord2")
◇ [Delphi] Save the file in the blob field
Function blobcontenttring (Const Filename: String): String;
begin
With tfilestream.create (Filename, FMOPENRD) Do
try
setlength (result, size);
Read (Pointer (Result)^, size);
finally
free;
end;
end;
// Save the field
begin
If (OpenDialog1.execute) then
begin
sfilename: = OpenDialog1.filename;
adotable1.edit;
adotable1.Fieldbyname ('Visio'). ASSTRING: = BlobContenttring (FILENAME);
adotable1.post;
end;
◇ [Delphi] Copy all the files to the clipboard
Use ShlobJ, Activex, CLIPBRD;
ProceDure TFORM1.COPYTOCLIPBRD (VAR FILENAME: 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: = GlobalLOC (gmem_share or gmem_zeroinit, sizeof (TDROPFILES)+Length (FileName) +1);
if Medium.hglobal <> 0 then Begin
Medium.tymed: = type_hglobal;
DropFiles: = GlobalLock (Medium.hglobal);
try
drapfiles^.pfiles: = sizeof (tdropfiles);
drapfiles^.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 operation process
uses tlhelp32;
procedure TForm1.Button1Click(Sender: TObject);
var lppe: TPROCESSENTRY32;
Found: Boolean;
Hand: THANDLE;
begin
Hand: = CreateToolHelp32snapshot (TH32CS_SNAPALL, 0);
Found: = process32Firs (hand, lppe);
While Found Do
begin
Listbox1.Items.add (strpas (lppe.szexefile);
Found: = process32next (hand, lppe);
end;
end;
◇ [Delphi] Establish 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.tableename: = 'New_table';
Table2.createtable ();
finally
Table2.free ();
end;
◇ [Delphi] The most dish understands of DLL establishment and reference
// First look at DLL Source (File-> New-> DLL)
library project1;
uses
Sysutils, classses;
Function addit (f: Integer; s: Integer): Integer; Export;
begin
Makeasum: = f+s;
end;
exports
addit;
end.
// Call (in Ur Project)
implementation
Function addit (F: Integer; s: Integer): Integer; Far; External 'Project1'; //
{Calling is addit (2,4); results show 6}
◇ [Delphi] Dynamic reading program itself
function gesseelfsize: Integer;
var
f: file of byte;
begin
filemode: = 0;
assfile (f, application.exename);
reset (f);
Result: = filesize (f); // The unit is byte
closefile (f);
end;
◇ [delphi] Read BIOS information
With memo1.Lines do
begin
Addd ('Mainboardbiosname:'+^I+String (PCHAR (Ptr ($ Fe061)));
Addd ('Mainboardbioscopyright:'+^I+String (PCHAR (PTR ($ Fe091)));););
Addd ('Mainboardbiosdate:'+^I+String (PCHAR (Ptr ($ FFFF5)));
Addd ('MainboardBiosserialno:'+^I+String (PCHAR (PTR ($ Fec71))););
end;
◇ [delphi] Dynamic establishment of MSSQL alias
procedure TForm1.Button1Click(Sender: TObject);
var myList: tStringlist;
begin
MyList: = tstringlist.create;
try
With mylist do
begin
Add ('Server name = 210.242.86.2');
Addd ('database name = db');
Addd ('user name = 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 ('user name = sa');
Database1.params.add ('password =');
Database1.connect: = true;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Database1.connect: = false;
Session1.Deletealias ('testsql');
end;
◇ [delphi] Play background music
Use MMSYSTEM
// Play music
Mcisendstring ('Open E: /1.mid Type Sequenceer Alias nn', '', 0, 0);
Mcisendstring ('Play nn from 0', '', 0, 0);
Mcisendstring ('Close Animation', '', 0, 0);
end;
// Stop playing
Mcisendstring ('Open E: /1.mid Type Sequenceer Alias nn', '', 0, 0);
Mcisendstring ('Stop nn', '', 0, 0);
Mcisendstring ('Close Animation', '', 0, 0);
◇ [Delphi] interface and a sample code of the class
Type {interface and class statement: The difference is that the data member, any non -public method, and public methods cannot be displayed in the interface.
IsAMPLE = interface // Definition isample interface
function getstring: string;
end;
TSAMPLE = Class (TinterfaceDObject, isample)
public
function getstring: string;
end;
// fundction definition
function tsample.getstring: string;
begin
result: = 'What Show is';
end;
// Call the class object
var sample: tsample;
begin
sample: = tsample.create;
showMessage (SAMPLE.GetString+'Class Object!');
sample.free;
end;
// Call the interface
var SampleInterface: Isample;
sample: tsample;
begin
sample: = tsample.create;
SampleInterface: = Sample; // Interface implementation must use Class
{The above two lines can also be made to reach SAMPLEINTERFACE: = tsample.create;}
showMessage (SampleInterface.getString+'Interface!');
//sample.free; {and local class, automatic release of the class in interface}
sampleInterface: = nil; {Release interface object}
end;
◇ [Delphi] The task bar is not the program
var
ExtendedStyle: Integer;
begin
Application.Initialize;
ExtendedStyle: = getwindowlong (application.handle, gwl_exStyle);
SetWindowlong (Application.handle, GWL_EXSSSTYLE, ExtendStyle OR WS_EX_TOOLWIW and Not WS_EX_APPWINDOW);
Application.CreateForm(TForm1, Form1);
Application.Run;
end.
◇ [Delphi] Alt+Ctrl+Del can't see the program
Add a statement after Implementation:
Function RegisterServiceProcess (DWPROCESSID, DWTYPE: Integer): Integer; Stdcall; External 'Kernel32.dll';;
RegiserviceProcess (GetCurrentProcessid, 1); // Hide
RegisterServiceProcess (GetCurrentProcessid, 0); // Display
◇ [delphi] detect the optical drive symbol
Var Drive: Char;
CDROMID: Integer;
begin
for drive: = 'd' to 'z' do
begin
cdromid: = getDriveType (pchar (drive+':/'));
if cdromid = 5 the showmessage ('Your optical drive is:'+drive+'disk!');
end;
end;
◇ [delphi] detection card
if AuxgetNumDevs () <= 0 Then Showmessage ('No Soundcard Found!') Else Showmessage ('Any Soundcard Found!');
◇ [Delphi] Drawing in the string grid
Stringgrid.ondrawcell event
With stringgrid1.canvas do
Draw (RECT.LEFT, Rect.top, Image1.picTure.graphic);
◇ [SQL Server] Another way of instead of the Like statement in SQL
For example, finding the user name contains all users "C", you can use it
Use mydatabase
Select * from table1 where username like '%c%"
The following is another way to complete the above function:
Use mydatabase
Select * From Table1 where charingex ('c', username)> 0
This method is theoretically one more judgment statement than the previous method, that is,> 0, but this judgment process is the fastest. I want to believe that more than 80%of the operations are spent to find words
The string and other operations, so it is not a big deal to use the Charindex function. It is also good to use this method, that is, for%, |, etc.
The found characters can be used directly in Charindex, as follows:
Use mydatabase
Select * From Table1 where charingex ('%', username)> 0
It can also be written:
Use mydatabase
Select * From Table1 where charingex (char (37), username)> 0
ASCII's characters are%%
◇ [Delphi] SQL Display Data/Tables
Select distance a.bianhao, a.xingming, b.Gongzi from "jianjie.dbf" a, "gongzi.dbf" b
Where a.bianhao = b.bianhao
◇ [Delphi] RFC (Request for Comment) related
IETF (Internet Engineering Task Force) Maintenance of RFC document http://www.ietf.cnri.reston.va.us
RFC882: The head standard structure of the message
RFC1521: MIME Part 1, Method of Transmission Merchants
RFC1945: Multimedia document transmission document
◇ [Delphi] The use of TNMUPROCESOR
Var Instream, Outstream: TFILESTREAM;
begin
Instream: = tfilestream.create (infile.txt, fmopenream);
Outstream: = tfilestream (outfile.txt, fmcreate);
Nmuue.method: = uucode; {uuencode/decode}
//Nmuue.method:=uumime; {mime}
Nmuue.inputStream: = Instream;
Nmuue.outputStream: = Outstream;
Nmuue.encode; {Code processing}
//Nmuue.decode; {decoding processing}
Instream.free;
outstream.free;
end;
◇ [Delphi] Operation of tfilestream
// Read the count byte from the file flow current position to the buffer buffer
function read (var buffer; count: longint): longint; override;
// Read the buffer buffer into the file stream
function write (const buffer; count: longint): longint; override;
// Set the file stream. The current reading and writing pointer is Offset
Function Seek (Office: Longint; Origin: Word): Longint; Override;
Origin = {Sofrombeginning, Sofromcurrent, Sofromend}
// Copy Count from the current position of the current position in another file flow to the current position of the current file stream
Function Copyfrom (Source: TSTREAM; Count: Longint): longint;
// Read the specified file to the file flow
var myfstream: tfilestream;
begin
myfstream: = tfilestream.create (OpenDialog1.Filename, FMOPENREAD);
end;
[JavaScript] Detect whether to install the IE plug -in Shockwave & Quicktime
<script language = "javascript">
var myplugin = navigator.plugins ["shockwave"];
if (MyPlugin)
document.writeln ("You have installed Shockware!")
else
document.writeln ("You haven't installed ShockWave!")
</script> <br>
<script language = "javascript">
var myplugin = navigator.plugins ["quicktime"];
if (MyPlugin)
document.writeln ("You have installed Quicktime!")
else
document.writeln ("You haven't installed Quicktime!")
</script>
[Internet] Table references iframe effect
<table cellpadding="0" cellspacing="0">
<tr>
<td> <ielay ID = "ad1" visibility = "hidden"> </iLayer> <nolayer> <iFray SRC = "I: /jinhtml/zj/h21.htm" Marginwidth = "0" Marginheight = "110" E = "10" vspace = "20" frameborder = "0" scrolling = "1"> </iframe> </nolay> </td>
</tr>
</table>
◇ [Delphi] Webbrowser control skills
1. Implement the printing function
var vain, vaout: olevariant;
Webbrowser.controlinterface.execwb (olecmdid_print, olecmdexecopt_dontpromptuser, vain, vaout);
2. WEBBROWSER read the page from the stream
function tform1.loadfromstream (constish: tStream): hresult;
begin
Astream.seek (0, 0);
Result: = (webbrowser1.document as iPersistStreaminit) .load (tStreamAdapter.create (Astream));
end;
3. "About:" Protocol Will Let You Navigate to An HTML String:
ProceDure TFORM1.loadmlstring (SHTML: String);
var Flags, targetFramename, Postdata, Headers: OLEVARIANT;
Webbrowser1.navigate ('About:' + Shtml, Flags, TargetFramename, Postdata, Headers)
4. "Res:" Protocol will Let You Navigate to An HTML FILE Stone as a Resource. More information is available from the microsoft site:
Procedure tform1.loadmlResource;
var Flags, targetFramename, Postdata, Headers: OLEVARIANT;
Webbrowser1.navigate ('Res: //' + Application.exename + '/MyHtml', Flags, TargetFramename, Postdata, Headers)
Use brcc32.exe to create resource files (*.rc)
MyHTML 23 "./html/myhtml.htm"
Morehtml 23 "./html/morehtml.htm"
{$ R html.res} //html.rc is compiled into html.res
5. Save the complete html file
var
Htmldocument: IHTMLDOCUMENT2;
PersistFile: iPersistFile;
begin
Htmldocument: = webbrowser1.document as IHTMLDOCUMENT2;
PersistFile: = HTMLDOCUMENT As iPersistFile;
PersistFile.save (StringToolestr ('Test.htm'), TRUE); TRUE)
While HTMLDOCUMENT.READYSTATE <> 'Complete' Do
Application.processMessages;
end;
◇ [Delphi] Install Webbrowser control (embedded IE control)
You must first determine that the system has been installed with internet Explorer4 or later versions. The Delphi menu- component--imported activex control. Select the microSoft Internet Controls "and ADD in a existing package file. The WebBrowser control will be displayed in A CTIVEX control panel .
◇ [Delphi] Implementing Windows2000 translucent windows
Function SetlayeredWindowattributes (HWND: Hwnd; CRKEY: Longint; Balpha: byte; DWFLAGS: Longint): Longint; External User32; // Functional Declaration
procedure TForm1.FormCreate(Sender: TObject);
var longint;
begin
L: = getwindowlong (handle, gwl_exStyle);
L: = l or $ 80000;
Setwindowlong (handle, gwl_exStyle, L);
SetlayeredWindowattributes (Handle, 0, 180, 2);
end;
◇ [Delphi] Program Display Advertising Webbrowser loading pictures
var Flag, Frame, PData, Header: Olevariant;
begin
Webbrowser1.navigate ('http://www.chineseall.com/images/logo.jpg', Flag, Frame, PData, Header)
end;
◇ [Delphi] Calculate the size of a directory
Function GetDirectorySize (Const Adirectory: String): Integer;
var
DIR: TsearchRec;
RET: Integer;
PATH: String;
begin
Result := 0;
PATH: = ExtractFilePath (adirectory);
RET: = Sysutils.findFirs (adirectory, faanyfile, dir);
if RET <> No_error THEN
exit;
try
While Ret = no_error do
begin
Inc (Result, Dir.size);
// If it is a directory, and not '.' Or '..'
If (Dir.attr in [FADIRECTORY]) and (Dir.name [1] <> <> '.')
Inc (result, getdirectorysize (Path + Dir.name + '/*.*'));
Ret: = Sysutils.findnext (DIR);
end;
finally
Sysutils.findClose (dir);
end;
end;
◇ [delphi] Clear a directory
Function Emptydirectory (Thedirectory: String; Recursive: Boolean):
Boolean;
var
Search great: tSearchold;
Res: Integer;
begin
Result: = false;
Thedirectory: = normaldir (thedirectory);
Res: = FindFirs (TheDirectory + '*.*', FAANYFILE, SEARCHREC);
try
While res = 0 do
begin
if (SearchRec.name <> '.') and (Search great <> '..') then
begin
If (SearchRec.attr and Fadirectory)> 0) and recursive
then begin
Emptydirectory (ThireRCTORY + SearchRec.name, True);
RemoveDirectory (PCHAR (Thedirectory + SearchRc.name));
end
else begin
Deletefile (PCHAR (TheDirectory + SearchRec.name))
end;
end;
Res: = findnext (search);
end;
Result := True;
finally
FindClose (SearchRec.findhandle);
end;
end;
◇ [Delphi] Release ADO program installation ADO
Run once MDAC_TYP.EXE, which is available in Microsoft's Windows, IE, Office, Visual Studio.
The directory after the installation of the installation program is the same as the directory path set in the program. C:/Program Files/Common Files/System/Ado folder is in the ADO component. The access2000 has Ado2.1. Compilation wants to remove the hook of Build with Runtime Library in the Project-> Option-> Packages dialog box.
◇ [Delphi] Intercepting Windows system message: WM_Close message
Procedure wmclose (varm msg: tmessage); Message wm_close;
Procedure tmainform.wmclose (VAR MSG: TMESSAGE);
begin
m_bclosenoquery: = false;
inherited;
end;