DELPHI基礎開發技巧
◇[DELPHI]網路鄰居複製文件
usesshellapi;
copyfile(pchar('newfile.txt'),pchar('//computername/direction/targer.txt'),false);
◇[DELPHI]產生滑鼠拖曳效果
透過MouseMove事件、DragOver事件、EndDrag事件實現,例如在PANEL上的LABEL:
varxpanel,ypanel,xlabel,ylabel:integer;
PANEL的MouseMove事件:xpanel:=x;ypanel:=y;
PANEL的DragOver事件:xpanel:=x;ypanel:=y;
LABEL的MouseMove事件:xlabel:=x;ylabel:=y;
LABEL的EndDrag事件:label.left:=xpanel-xlabel;label.top:=ypanel-ylabel;
◇[DELPHI]取得WINDOWS目錄
usesshellapi;
varwindir:array[0..255]ofchar;
getwindowsdirectory(windir,sizeof(windir));
或從登錄中讀取,位置:
HKEY_LOCAL_MACHINE/Software/Microsoft/Windows/CurrentVersion
SystemRoot鍵,取得如:C:/WINDOWS
◇[DELPHI]在FORM或其他容器上畫線
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]字串清單使用
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]簡單的剪貼簿操作
richedit1.selectall;
richedit1.copytoclipboard;
richedit1.cuttoclipboard;
edit1.pastefromclipboard;
◇[DELPHI]關於文件、目錄操作
Chdir('c:/abcdir');轉到目錄
Mkdir('dirname');建立目錄
Rmdir('dirname');刪除目錄
GetCurrentDir;//取目前目錄名,無'/'
Getdir(0,s);//取工作目錄名s:='c:/abcdir';
Deletfile('abc.txt');//刪除文件
Renamefile('old.txt','new.txt');//檔案更名
ExtractFilename(filelistbox1.filename);//取檔名
ExtractFileExt(filelistbox1.filename);//取檔案後綴
◇[DELPHI]處理文件屬性
attr:=filegetattr(filelistbox1.filename);
if(attrandfaReadonly)=faReadonlythen...//唯讀
if(attrandfaSysfile)=faSysfilethen...//系統
if(attrandfaArchive)=faArchivethen...//存檔
if(attrandfaHidden)=faHiddenthen...//隱藏
◇[DELPHI]執行程序外文件
WINEXEC//呼叫可執行文件
winexec('command.com/ccopy*.*c:/',SW_Normal);
winexec('startabc.txt');
ShellExecute或ShellExecuteEx//啟動檔案關聯程序
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]取得系統運作的進程名
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]關於彙編的嵌入
AsmEnd;
可以任意修改EAX、ECX、EDX;不能修改ESI、EDI、ESP、EBP、EBX。
◇[DELPHI]關於型別轉換函數
FloatToStr//浮點轉字串
FloatToStrF//帶格式的浮點轉字串
IntToHex//整數轉16進位
TimeToStr
DateToStr
DateTimeToStr
FmtStr//依指定格式輸出字串
FormatDateTime('YYYY-MM-DD,hh-mm-ss',DATE);
◇[DELPHI]字串的過程和函數
Insert(obj,target,pos);//字串target插入在pos的位置。如插入結果大於target最大長度,多出字元將被截掉。如Pos在255以外,會產生運轉錯。例如,st:='Brian',則Insert('OK',st,2)會使st變成'BrOKian'。
Delete(st,pos,Num);//從st字串中的pos(整數)位置開始刪除數為Num(整數)個字元的子字串。例如,st:='Brian',則Delete(st,3,2)將變為Brn。
Str(value,st);//將數值value(整數或實型)轉換成字串放在st中。例如,a=2.5E4時,則str(a:10,st)將使st的值為'25000'。
Val(st,var,code);//把字串表達式st轉換為對應整數或實型數值,存放在var中。 St必須是一個表示數值的字串,並且符合數值常數的規則。在轉換過程中,如果沒有偵測出錯誤,變數code置為0,否則置為第一個出錯字元的位置。例如,st:=25.4E3,x是一個實型變數,則val(st,x,code)將使X值為25400,code值為0。
Copy(st.pos.num);//返回st字串中一個位置pos(整數)處開始的,含有num(整數)個字元的子字串。如果pos大於st字串的長度,那就會傳回一個空字串,如果pos在255以外,會引起運行錯誤。例如,st:='Brian',則Copy(st,2,2)回傳'ri'。
Concat(st1,st2,st3……,stn);//把所有自變數表示出的字串按所給的順序連接起來,並傳回連接後的值。如果結果的長度255,將產生運行錯誤。例如,st1:='Brian',st2:='',st3:='Wilfred',則Concat(st1,st2,st3)回傳'BrianWilfred'。
Length(st);//傳回字串表達式st的長度。例如,st:='Brian',則Length(st)回傳值為5。
Pos(obj,target);//傳回字串obj在目標字串target的第一次出現的位置,如果target沒有匹配的字串,Pos函數的回傳值為0。例如,target:='BrianWilfred',則Pos('Wil',target)的回傳值是7,Pos('hurbet',target)的回傳值是0。
◇[DELPHI]關於處理註冊表
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]關於鍵盤常數名
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]初步判斷程序母語
DELPHI軟體的DOS提示:ThisPRogramMustBeRunUnderWin32.
VC++軟體的DOS提示:ThisProgramCannotBeRunInDOSMode.
◇[DELPHI]操作Cookie
response.cookies("name").domain:='http://www.086net.com';
withresponse.cookies.adddo
begin
name:='username';
value:='username';
end
◇[DELPHI]增加到文件選單連接
usesshellapi,shlOBJ;
shAddToRecentDocs(shArd_path,pchar(filepath));//增加連接
shAddToRecentDocs(shArd_path,nil);//清空
◇[雜類]備份智能ABC輸入法詞庫
windows/system/user.rem
windows/system/tmmr.rem
◇[DELPHI]判斷滑鼠按鍵
ifGetAsyncKeyState(VK_LButton)<>0then...//左鍵
ifGetAsyncKeyState(VK_MButton)<>0then...//中鍵
ifGetAsyncKeyState(VK_RButton)<>0then...//右鍵
◇[DELPHI]設定窗體的最大顯示
onFormCreate事件
self.width:=screen.width;
self.height:=screen.height;
◇[DELPHI]按鍵接受訊息
OnCreate事件中處理:application.OnMessage:=MyOnMessage;
procedureTForm1.MyOnMessage(varMSG:TMSG;varHandle:Boolean);
begin
ifmsg.message=256then...//ANY鍵
ifmsg.message=112then...//F1
ifmsg.message=113then...//F2
end;
◇[雜類]隱藏共用資料夾
共享效果:可存取,但不可見(在資源管理、網路鄰居)
取共享名為:direction$
訪問://computer/dirction/
◇[javaScript]JavaScript網頁常用效果
網頁60秒定時關閉
關閉視窗
關閉
定時轉URL
在運行也可能配置TQuery,具體見Delphi幫助。
□◇[DELPHI]得到圖像上某一點的RGB值
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]關於日期格式分解轉換
varyear,month,day:Word;now2:Tdatatime;
now2:=date();
decodedate(now2,year,month,day);
lable1.Text:=inttostr(year)+'年'+inttostr(month)+'月'+inttostr(day)+'日';
◇[DELPHI]如何判斷目前網路連線方式
判斷結果是MODEM、區域網路或代理伺服器方式。
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]如何判斷字串是否為有效EMAIL位址
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]判斷系統是否連接INTERNET
需要引入URL.DLL中的InetIsOffline函數。
函數申明為:
functionInetIsOffline(Flag:Integer):Boolean;stdcall;external'URL.DLL';
然後就可以呼叫函數判斷系統是否連接到INTERNET
ifInetIsOffline(0)thenShowMessage('notconnected!')
elseShowMessage('connected!');
此函數傳回TRUE如果本機系統沒有連接到INTERNET。
附:
大多數裝有IE或OFFICE97的系統都有此DLL可供呼叫。
InetIsOffline
BOOLInetIsOffline(
DWORDdwFlags,
);
◇[DELPHI]簡單地播放和暫停WAV文件
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]取機器BIOS訊息
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]網路下載文件
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]解析伺服器IP位址
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]取得快捷方式中的連接
functionExeFromLink(constlinkname:string):string;
var
FDir,
FName,
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]控制TCombobox的自動完成
{'Sorted'propertyoftheTComboboxtotrue}
varlastKey:Word;//全域變量
//TCombobox的OnChange事件
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;
//TCombobox的OnKeyDown事件
procedureTForm1.AutoCompleteKeyDown(Sender:TObject;varKey:Word;
Shift:TShiftState);
begin
lastKey:=Key;
end;
◇[DELPHI]如何清空一本目錄
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]如何計算一個目錄的大小
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]安裝程式如何加入到Uninstall列表
操作註冊表,如下:
1.在HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall鍵下建立一個主鍵,名稱任意。
範例HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall/MyUninstall
2.在HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall/MyUnistall下鍵兩個字串值,
這兩個字串值的名稱是特定的:DisplayName和UninstallString。
3.給予字串DisplayName賦值為顯示在「刪除應用程式清單」中的名稱,如'AimingUninstallone';
將字串UninstallString賦值為執行的刪除指令,如C:/WIN97/uninst.exe-f"C:/TestPro/aimTest.isu"
◇[DELPHI]截獲WM_QUERYENDsession關機訊息
type
TForm1=class(TForm)
procedureWMQueryEndSession(varMessage:TWMQueryEndSession);messageWM_QUERYENDSESSION;
procedureCMEraseBkgnd(varMessage:TWMEraseBkgnd);MessageWM_ERASEBKGND;
private
{Privatedeclarations}
public
{Publicdeclarations}
end;
procedureTForm1.WMQueryEndSession(varMessage:TWMQueryEndSession);
begin
Showmessage('computerisabouttoshutdown');
end;
◇[DELPHI]取得網路鄰居
proceduregetnethood();//NT做伺服器,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;//取得所有的域
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);
//取得所有的計算機
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]取得某一計算機上的共用目錄
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;//取得根結點
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]得到硬碟序號
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的自動翻頁
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');//上翻頁
end;
procedureTForm1.Button1Click(Sender:TObject);
begin
ScrollMemo(Memo1,'u');//下翻頁
end;
◇[DELPHI]DBGrid中回車到下個位置(Tab鍵)
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]如何安裝控件
安裝方法:
1.對於單一控制項,Component-->installcomponent..-->PAS或DCU檔案-->install
2.對於有*.dpk檔案的控制項包,File-->open(下拉列錶框中選*.dpk)-->install即可.
3.對於有*.dpl檔案的控制項包,InstallPackages-->Add-->dpl檔名即可。
4.如果以上Install按鈕為失效的話,試試Compile按鈕。
5.是runtimelib則在option下的packages下的runtimepackes加之.
如果編譯時提示檔找不到的話,一般是控制項的安裝目錄不在delphi的Lib目錄中,有兩種方法可以解決:
1.把安裝的原檔案拷入到delphi的Lib目錄下。
2.或Tools-->EnvironmentOptions中把控制項原程式碼路徑加入Delphi的Lib目錄中即可。
◇[DELPHI]目錄完全刪除(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]取得TMemo控制項目前遊標的行和列資訊到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);//行長
◇[DELPHI]讀取硬碟序號
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]CSS常用綜合技巧
1。 P:first-letter{font-size:300%;float:left}//首字會比一般字體加大三倍。
2。
3。嵌入一個樣式表
4。
Arial//SPAN接受STYLE、CLASS和ID屬性
DIV可以包含段落、標題、表格甚至其它部分
5。
6。 //定義見3。 7。屬性列表 字體風格:font-style:[normal|italic|oblique]; 字體大小:font-size:[xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|<長度>|<百分比>] 文字修飾:text-decoration:[underline||overline||line-through||blink] 文字轉換:text-transform:[none|capitalize|uppercase|lowercase] 背景顏色:background-color:[<顏色>|transparent] 背景圖象:background-image:[ 行高:line-height:[normal|<數字>|<長度>|<百分比>] 邊框樣式:border-style:[none|dotted|dashed|solid|double|groove|ridge|inset|outset] 漂浮:float:[left|right|none] 8。長度單位 相對單位: em(em,元素的字體的高度) ex(x-height,字母"x"的高度) px(像素,相對於螢幕的解析度) 絕對長度: in(英吋,1英吋=2.54公分) cm(公分,1公分=10毫米) mm(米) pt(點,1點=1/72吋) pc(帕,1帕=12點) ◇[DELPHI]VCL製作簡要步驟 1.建立部件屬性方法事件 (建立庫單元,繼承為新的類型,新增屬性、方法、事件,註冊部件,建立包檔) 2.訊息處理 3.異常處理 4.部件可視 ◇[DELPHI]動態連結函式庫的裝載 靜態載入:procedurename;external'lib.dll'; 動態裝載:varhandle:Thandle; handle:=loadlibrary('lib.dll'); ifhandle<>0then begin {dosomething} freelibrary(handle); end; ◇[DELPHI]指標變數和位址 varx,y:integer;p:^integer;//指向INTEGER變數的指針 x:=10;//變數賦值 p:=@x;//變數x的位址 y:=p^;//為Y賦值指標P @@procedure//傳回過程變數的記憶體位址 ◇[DELPHI]判斷字符是漢字的一個字符 ByteType('你好haha嗎',1)=mbLeadByte//是第一個字符 ByteType('你好haha嗎',2)=mbTrailByte//是第二個字符 ByteType('你好haha嗎',5)=mbSingleByte//不是中文字符 ◇[DELPHI]memo的定位操作 memo1.lines.delete(0)//刪除第1行 memo1.selstart:=10//定位10位元組處 ◇[DELPHI]取得雙位元組字元內碼 functiongetit(s:string):integer; begin Result:=byte(s[1])*$100+byte(s[2]); end; 使用:getit('計')//$bcc6即十進位48326 ◇[DELPHI]呼叫ADD資料儲存過程 預存程序如下: createprocedureaddrecord( record1varchar(10) record2varchar(20) ) as begin insertintotablename(field1,field2)values(:record1,:record2) end 執行預存程序: EXECUTEprocedureaddrecord("urrecord1","urrecord2") ◇[DELPHI]將檔案存到blob欄位中 functionblobcontenttostring(constfilename:string):string; begin withtfilestream.create(filename,fmopenread)do try setlength(Result,size); read(Pointer(Result)^,size); finally free; end; end; //保存字段 begin if(opendialog1.execute)then begin sFileName:=OpenDialog1.FileName; adotable1.edit; adotable1.fieldbyname('visio').asstring:=Blobcontenttostring(FileName); adotable1.post; end; ◇[DELPHI]把檔案全部複製到剪貼簿 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]列舉目前系統運行進程 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]根據BDETable1建立新表Table2 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]最菜理解DLL建立與引用 //先看DLLsource(FILE-->NEW-->DLL) libraryproject1; uses SysUtils,Classes; functionaddit(f:integer;s:integer):integer;export; begin makeasum:=f+s; end; exports addit; end. //呼叫(INurPROJECT) implementation functionaddit(f:integer;s:integer):integer;far;external'project1';//申明 {呼叫就是addit(2,4);結果顯示6} ◇[DELPHI]動態讀取程式本身大小 functionGesSelfSize:integer; var f:fileofbyte; begin filemode:=0; assignfile(f,application.exename); reset(f); Result:=filesize(f);//單位是位元組 closefile(f); end; ◇[DELPHI]讀取BIOS訊息 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]動態建立MSSQL別名 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]播放背景音樂 usesmmsystem //播放音樂 MCISendString('OPENe:/1.MIDTYPESEQUENCERALIASNN','',0,0); MCISendString('PLAYNNFROM0','',0,0); MCISendString('CLOSEANIMATION','',0,0); end; //停止播放 MCISendString('OPENe:/1.MIDTYPESEQUENCERALIASNN','',0,0); MCISendString('STOPNN','',0,0); MCISendString('CLOSEANIMATION','',0,0); ◇[DELPHI]介面和類別的一個範例程式碼 Type{介面與類別申明:差別在於無法在介面中申明資料成員、任何非公有的方法、公共方法不使用PUBLIC關鍵字} Isample=interface//定義Isample接口 functiongetstring:string; end; Tsample=class(TInterfacedObject,Isample) public functiongetstring:string; end; //function定義 functionTsample.getstring:string; begin result:='whatshowis'; end; //呼叫類別物件 varsample:Tsample; begin sample:=Tsample.create; showmessage(sample.getstring+'classobject!'); sample.free; end; //呼叫介面 varsampleinterface:Isample; sample:Tsample; begin sample:=Tsample.create; sampleInterface:=sample;//Interface的實作必須使用class {以上兩行也可表達成sampleInterface:=Tsample.create;} showmessage(sampleInterface.getstring+'Interface!'); //sample.free;{和局部類別不同,Interface中的類別自動釋放} sampleInterface:=nil;{釋放介面物件} end; ◇[DELPHI]任務條就看不當程序 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看不到程式 在implementation後面加上聲明: functionRegisterServiceProcess(dwProcessID,dwType:Integer):Integer;stdcall;external'KERNEL32.DLL'; RegisterServiceProcess(GetCurrentProcessID,1);//隱藏 RegisterServiceProcess(GetCurrentProcessID,0);//顯示 ◇[DELPHI]偵測光碟機符號 vardrive:char; cdromID:integer; begin fordrive:='d'to'z'do begin cdromID:=GetDriveType(pchar(drive+':/')); ifcdromID=5thenshowmessage('你的光碟機為:'+drive+'碟盤!'); end; end; ◇[DELPHI]檢測音效卡 ifauxGetNumDevs()<=0thenshowmessage('Nosoundcardfound!')elseshowmessage('Anysoundcardfound!'); ◇[DELPHI]在字串網格中畫圖 StringGrid.OnDrawCell事件 withStringGrid1.Canvasdo Draw(Rect.Left,Rect.Top,Image1.Picture.Graphic); ◇[SQLSERVER]SQL中取代Like語句的另一種寫法 例如查找用戶名包含有"c"的所有用戶,可以用 usemydatabase select*fromtable1whereusernamelike'%c%" 以下是完成上面功能的另一種寫法: usemydatabase select*fromtable1wherecharindex('c',username)>0 這種方法理論上比上一種方法多了一個判斷語句,即>0,但這個判斷過程是最快的,我想信80%以上的運算都是花在查找字 符串及其它的運算上,所以運用charindex函數也沒什麼大不了.用這種方法也有好處,那就是對%,|等在不能直接用like 查找到的字符中可以直接在這charindex中運用,如下: usemydatabase select*fromtable1wherecharindex('%',username)>0 也可以寫成: usemydatabase select*fromtable1wherecharindex(char(37),username)>0 ASCII的字元即為% ◇[DELPHI]SQL顯示多資料庫/表 SELECTDISTINCTA.bianhao,a.xingming,b.gongziFROM"jianjie.dbf"a,"gongzi.DBF"b WHEREA.bianhao=b.bianhao ◇[DELPHI]RFC(RequestForComment)相關 IETF(InternetEngineeringTaskForce)維護RFC文件http://www.ietf.cnri.reston.va.us RFC882:封包頭標結構 RFC1521:MIME第一部分,傳輸封包方法 RFC1945:多媒體文件傳輸文檔 ◇[DELPHI]TNMUUProcessor的使用 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;{編碼處理} //NMUUE.Decode;{解碼處理} inStream.free; outStream.free; end; ◇[DELPHI]TFileStream的操作 //從檔案流目前位置讀count位元組到緩衝區BUFFER functionread(varbuffer;count:longint):longint;override; //將緩衝區BUFFER讀取到檔案流中 functionwrite(constbuffer;count:longint):longint;override; //設定檔案流目前讀寫指標為OFFSET functionseek(offset:longint;origin:word):longint;override; origin={soFromBeginning,soFromCurrent,soFromEnd} //從另一文件流中目前位置複製COUNT到目前文件流目前位置 functioncopyfrom(source:TStream;count:longint):longint; //讀指定檔案到檔案流 varmyFStream:TFileStream; begin myFStream:=TFileStream.create(OpenDialog1.filename,fmOpenRead); end; [Javascript]偵測是否安裝IE插件Shockwave&Quicktime ----------------- 謝謝你耐心看完,有技巧了,希望繼續貼出來!