小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

delphi十個小技巧

 容心居 2021-04-19

1、判斷一個字符串是否包含于另外一個字符串的方法

      例如:if pos('ab','abcd')<>0 then

           messagedlg('ab是包含于abcd',mtConfirmation,[mbYes,      mbNo],0);

     pos(obj,target) target字符串中找出第一個出現(xiàn)obj的第一個字符位置,如果找不到,返回0.

2、如何使窗口全屏,類似游戲一樣,而不是窗口的最大化!

      (1)BorderStyle bsNone

      (2)Windowstate wsMaximized

      (3) 退出時可加一個按鈕之類的,寫上 close 即可退出。

3、數(shù)字格式化輸出

     format('%8.2f',[123.456]),返回字符串'123.46'

4、播放一個wav文件

      usemmsystem;

     SndPlaySound('hello.wav',SND_FILENAME or SND_SYNC);

5、InputBox,InputQuery和ShowMessage函數(shù)的威力

      usesdialogs;

      vars,s1:string;

          b:boolean;

      begin

       s:=trim(Inputbox('NewPassword','Password','masterkey'));

        b:=s<>'';

        s1:=s;

        if b then b:=InputQuery('ConfirmPassword','Password',s1);

        if not b or (s1<>s) thenShowMessage('Password       Failed');

      end;

6、幾個有關子目錄的操作的過程

      MkDir(str);   ChDir(str);   GetDir(DriveID,str);       SetCurrentDir(str);

      IOResult --上面幾個過程調(diào)用成功即返回0

7、將一個可視控件變成圖形類型

      例如將一個帶背景的LABEL變成一個TIMAGE圖片類型,可以這樣做:

        image1.width:=label1.width;

        image1.height:=label1.height;

       label1.perform(WM_PAINT,image1.Canvas.Handle,0);

 

8、如何得到字符的ASCII值

        得到字符的ASCII值,可以用如下語句:

          var: a:integer;

           string1:string;

          begin

           string1:='ABC';

           a:=byte(string[1]); {此時就得到'A'ASCII}

          end;

9、動態(tài)更新DBGrid的顏色

        例如,如果一個城市的人口大于200萬,我們就讓它顯示為藍色。使用的控件事件為DBGrid.OnDrawColumeCell

      procedureTForm1.DBGrid1DrawColumnCell(Sender:       TObject; const Rect:TRect;DataCol:Integer; Column: TColumn; State:       TGridDrawState);

      begin

        ifTable1.FieldByName('Population').AsInteger       > 20000000 then           DBGrid1.Canvas.Font.Color := clBlue;

        DBGrid1.DefaultDrawColumnCell(Rect,DataCol, Column, State);      end;

10、獲得命令行參數(shù)

        1. 取得命令列參數(shù)的個數(shù): ParamCount 函數(shù)

        2. 呼叫 ParamStr(0), 傳回執(zhí)行檔的檔名(含路徑)

        3. 呼叫ParamStr(n), 傳回第n個參數(shù)的內(nèi)容

        例子:

      procedureTForm1.FormCreate(Sender: TObject);

      var

       ix: integer;

      begin

       Memo1.Lines.Clear;

       if ParamCount = 0 then

        Memo1.Lines.Add('沒有參數(shù)')

       else

       begin

        Memo1.Lines.Add('檔名:' + ParamStr(0));

        for ix := 1 to ParamCount do

        Memo1.Lines.Add(ParamStr(ix));

       end;

      end;

delphi小技巧兩則轉(zhuǎn)自逸仙時空 

最近在研究類及類方法時發(fā)現(xiàn)一些很有趣的用法,這里挑出兩則最有用的與大家分享?!?nbsp;

一、訪問保護屬性 

眾所周知,delphi的對象有private、protected和public三個級別的訪問控制。而delphi有一個奇怪的規(guī)則,就是在同一個unit里的對象可以互相訪問對方的protected級別屬性! 

利用這個特性,我們可以輕松訪問任意對象的protected級別屬性。雖然這樣不是很符合面向?qū)ο缶幊痰姆庋b的思想,但有時的確是非常有用的。比如在使用TDBGrid時,我們對如何獲得其Row和Col非常頭疼,其實在TDBGrid中,Row和Col都是protected級別的屬性,我們只要在需要使用這兩個屬性的unit的interface里聲明   

TFakeGrid =class(TDBGrid);   

然后就可以使用TFakeGrid(ADBGrid).Row和TFakeGrid(ADBGrid).Col輕松訪問了,這個規(guī)則對protected里的方法同樣適用?! ?nbsp;

二、類方法的使用類方法(Classmethods)是一類特殊的方法,它們在聲明時要以class開頭  

type  

TFigure =class  

public  ... 

classprocedure GetInfo(var Info: TFigureInfo); 

virtual;  

...  

end;   

實現(xiàn)時也以class開頭  

classprocedure TFigure.GetInfo(var Info: TFigureInfo);  

begin 

... 

end;  

(具體意義請自行查看幫助)    

乍一看好象平時沒有遇到過這個東東,也沒有看到過誰用過這個東東,好象這個東東也沒有什么大作用,其實不然……  比如我們有時為輸入密碼或其他常用數(shù)據(jù)專門做一個form,但由于其代碼都在form定義的unit里面,所以在使用時僅僅需要幾行代碼,比如 

withTfrmPassword.Create(nil) 

do   

try 

ShowModal;  

finally  

Free;  

end;   

雖然這樣的代碼已經(jīng)很簡潔,但如果寫個十七八個還是很討厭的。利用類方法可以使其更簡潔! 

一行足以……   

TfrmPassword= class(TForm)  

...   

public 

{ Publicdeclarations }   

classfunction Execute: TModalResult;   

end;  

... 

classfunction TfrmPassword.Execute: 

TModalResult;  

begin 

withTfrmPassword.Create(nil) 

do  

try   

Result :=ShowModal;  

finally 

Release;//注意此處必須為release不能為free!  

end;  

end;  

然后只用一行   

TfrmPassword.Execute;     

即可直接完成調(diào)用……是否很爽^_^

 

 

1、檢測主程序大小,防止破解補丁之類:

FunctionTForm1.GesSelfSf: integer;

var

F: file ofbyte;

begin

   Filemode:=0;

   Assignfile(F,'.\FileName.exe');

   Reset(f);

   Result:=Filesize(F);

   Closefile(F);

end;

2、檢測創(chuàng)建日期和時間,讓破解補丁實效:

FunctionTForm1.FinDate:String;

var

t:TDate;

begin

   ShortDateFormat:='yyyy-mm-dd';

   t:=FileDateToDateTime(FileAge('FileName.exe'));

   Result:=DateToStr(t);

end;

3、注冊碼加密函數(shù)嵌入數(shù)學函數(shù),增加破解難度:

(略)

4、必要時自己刪除自己(主程序):

procedureTForm1.Funll;

var

hModule:THandle;

buff:array[0..255]ofChar;

hKernel32:THandle;

pExitProcess,pDeleteFileA,pUnmapViewOfFile:Pointer;

begin

   hModule:=GetModuleHandle(nil);

   GetModuleFileName(hModule, buff, sizeof(buff));

   CloseHandle(THandle(4));

   hKernel32:=GetModuleHandle('KERNEL32');

   pExitProcess:=GetProcAddress(hKernel32, 'ExitProcess');

   pDeleteFileA:=GetProcAddress(hKernel32, 'DeleteFileA');

   pUnmapViewOfFile:=GetProcAddress(hKernel32, 'UnmapViewOfFile');

   asm

   LEA EAX, buff

   PUSH 0

   PUSH 0

   PUSH EAX

   PUSH pExitProcess

   PUSH hModule

   PUSH pDeleteFileA

   PUSH pUnmapViewOfFile

   RET

   end;

   begin

   Funll;

   end;

end;

網(wǎng)上找來的感覺對入門者很有啟示 收藏一下了!

No.1 判斷邏輯類型}

var B:Boolean;

begin

B :=Boolean(2); //這樣只是為了調(diào)試//B := True;

if B = Truethen ShowMessage('B = True'); //不建議//不安全

///

if B thenShowMessage('B'); //建議//簡短

end;

var B:Boolean;

begin

ifEdit1.Text = '是' then //不建議//煩瑣

B := True

else B :=False;

///

B :=Edit1.Text = '是'; //建議//簡短

end;

{ No.2臨時SQL查詢 }

begin

QueryTemp.Close;

QueryTemp.SQL.Text:= 'SELECT SUM(金額) AS 合計 FROM 銷售表';

QueryTemp.Open;//不建議//數(shù)據(jù)沒有關閉造成資源浪費

ShowMessage(Query1.FieldByName('合計').AsString);

/

QueryTemp.SQL.Text:= 'SELECT SUM(金額) AS 合計 FROM 銷售表';

QueryTemp.Open;

ShowMessage(Query1.FieldByName('合計').AsString);

QueryTemp.Close;//建議用//使用完就關閉

end;

{ No.3獲取記錄數(shù) }

var

vRecordCount:Integer;

begin

Query1.SQL.Text:= 'SELECT * FROM Table1'; //不建議//嚴重浪費資源,會取得很多不必要得信息

Query1.Open;

vRecordCount:= Query1.RecordCount;

Query1.Close;

/

Query1.SQL.Text:= 'SELECT COUNT(*) AS 記錄數(shù) FROM Table1'; //建議//快速有效、只處理一條記錄

Query1.Open;

vRecordCount:= Query1.FieldByName('記錄數(shù)').AsInteger;

Query1.Close;

ShowMessage(IntToStr(vRecordCount));

end;

{ No.4 字段賦值}

begin

Table1.Edit;

Table1.FieldByName('姓名').AsString:= Edit1.Text; //不建議

Table1.FieldByName('日期').AsDateTime:= Date;

/

Table1['姓名']:= Edit1.Text; //建議//簡短、擴充性好

//Table1.Fieldvalues['姓名']:= Edit1.Text; //Borland建議的方法。以及Paramvalues[]

Table1['日期']:= Date;

end;

{ No.5使用Self指針 }

begin

Edit1.Parent:= Form1; //不建議//Form1只是一個變量//如果沒有分配資源怎么辦?

///

Edit1.Parent:= Self; //建議

end;

{ No.6遍歷數(shù)據(jù)集 }

var

I: Integer;

begin

Query1.First;

for I := 0to Query1.RecordCount - 1 do begin //不建議//容易被影響

Query1.Next;

{};

end;

/

Query1.First;

while notQuery1.Eof do begin //建議

{ }

Query1.Next;

end;

end;

{ No.7利用Sender參數(shù),使代碼通用 }

procedureTForm1.Edit1Change(Sender: TObject);

begin

ifEdit1.Text = '' then //不建議

Edit1.Color:= clRed;

///

ifTEdit(Sender).Text = '' then //建議//復制到EditXChange中很方便

TEdit(Sender).Color:= clRed;

end;

{ No.8使用默認轉(zhuǎn)換函數(shù) }

var

I: Integer;

begin

I :=StrToInt(Edit1.Text); //不建議

///

I :=StrToIntDef(Edit1.Text,0);//建議//參考StrToFloatDef,StrToDateDef....不過這些只有Delphi6才有

end;

{ No.9 遍歷數(shù)組}

var

I: Integer;

A:array[0..9] of Integer;

begin

for I := 0to 9 do //不建議

A[I] := I;

///

for I :=Low(A) to High(A) do //建議//擴充性好

A[I] := I;

end;

{ No.10利用MaxInt常量 }

begin

Caption :=Copy(Edit1.Text, 3, Length(Edit1.Text) - 3 + 1); //不建議

///

Caption :=Copy(Edit1.Text, 3, MaxInt); //建議//嘻嘻,少計算一次

end;

{ No.11Result函數(shù)指針 }

functionFuncName: Boolean;

begin

FuncName :=True; //不建議//并且放在賦值號右邊不能當普通變量

///

Result :=True; //建議//擴充性好

end;

functionFuncSum(A: array of Integer): Integer;

var I:Integer;

begin

Result :=0;

for I :=Low(A) to High(A) do

Result :=Result + A[I]; //可不能用 FuncSum := FuncSum + A[I];

end;

{ No.12必須執(zhí)行的代碼、使用try ... finally ... end語句 }

var

vStringList:TStringList;

begin

vStringList:= TStringList.Create;

vStringList.LoadFromFile('c:\temp.txt');

ShowMessage(vStringList.Text);

vStringList.Free;//不建議//如果出現(xiàn)異常資源將無法釋放

///

vStringList:= TStringList.Create;

try

vStringList.LoadFromFile('c:\temp.txt');

ShowMessage(vStringList.Text);

finally//建議//即使出現(xiàn)Exit都會執(zhí)行

vStringList.Free;

end;

end;

//其他情況1

begin

Screen.Cursor:= crHourGlass;

try

{ 耗時操作 }

finally

Screen.Cursor:= crDefault;

end;

end;

//其他情況2

begin

Query1.DisableControls;

try

{ 操作數(shù)據(jù)集 }

finally

Query1.EnableControls;

end;

end;

◇[DELPHI]網(wǎng)絡鄰居復制文件

usesshellapi;

copyfile(pchar('newfile.txt'),pchar('//computername/direction/targer.txt'),false);

◇[DELPHI]產(chǎn)生鼠標拖動效果

通過MouseMove事件、DragOver事件、EndDrag事件實現(xiàn),例如在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] of char;

getwindowsdirectory(windir,sizeof(windir));

或者從注冊表中讀取,位置:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion

SystemRoot鍵,取得如:C:\WINDOWS

◇[DELPHI]在FORM或其他容器上畫線

varx,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]字符串列表使用

vartips:tstringlist;

tips:=tstringlist.create;

tips.loadfromfile('filename.txt');

edit1.text:=tips[0];

tips.add('lastline addition string');

tips.insert(1,'insertstring at NO 2 line');

tips.savetofile('newfile.txt');

tips.free;

◇[DELPHI]簡單的剪貼板操作

richedit1.selectall;

richedit1.copytoclipboard;

richedit1.cuttoclipboard;

edit1.pastefromclipboard;

◇[DELPHI]關于文件、目錄操作

Chdir('c:\abcdir');轉(zhuǎn)到目錄

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 (attrand faReadonly)=faReadonly then ... //只讀

if (attrand faSysfile)=faSysfile then ... //系統(tǒng)

if (attrand faArchive)=faArchive then ... //存檔

if (attrand faHidden)=faHidden then ... //隱藏

◇[DELPHI]執(zhí)行程序外文件

WINEXEC//調(diào)用可執(zhí)行文件

winexec('command.com/c copy *.* c:\',SW_Normal);

winexec('startabc.txt');

ShellExecute或ShellExecuteEx//啟動文件關聯(lián)程序

functionexecutefile(const filename,params,defaultDir:string;showCmd:integer):THandle;

ExecuteFile('C:\abc\a.txt','x.abc','c:\abc\',0);

ExecuteFile('http://tingweb.yeah.net','','',0);

ExecuteFile('mailto:tingweb@wx88.net','','',0);

◇[DELPHI]取得系統(tǒng)運行的進程名

varhCurrentWindow:HWnd;szText:array[0..254] of char;

begin

hCurrentWindow:=Getwindow(handle,GW_HWndFrist);

whilehCurrentWindow <> 0 do

begin

ifGetwindowtext(hcurrnetwindow,@sztext,255)>0 thenlistbox1.items.add(strpas(@sztext));

hCurrentWindow:=Getwindow(hCurrentwindow,GW_HWndNext);

end;

end;

◇[DELPHI]關于匯編的嵌入

Asm End;

可以任意修改EAX、ECX、EDX;不能修改ESI、EDI、ESP、EBP、EBX。

◇[DELPHI]關于類型轉(zhuǎn)換函數(shù)

FloatToStr//浮點轉(zhuǎn)字符串

FloatToStrF//帶格式的浮點轉(zhuǎn)字符串

IntToHex//整數(shù)轉(zhuǎn)16進制

TimeToStr

DateToStr

DateTimeToStr

FmtStr//按指定格式輸出字符串

FormatDateTime('YYYY-MM-DD,hh-mm-ss',DATE);

◇[DELPHI]字符串的過程和函數(shù) 

Insert(obj,target,pos);//字符串target插入在pos的位置。如插入結(jié)果大于target最大長度,多出字符將被截掉。如Pos在255以外,會產(chǎn)生運行錯。例如,st:='Brian',則Insert('OK',st,2)會使st變?yōu)?BrOKian'。 

Delete(st,pos,Num);//從st串中的pos(整型)位置開始刪去個數(shù)為Num(整型)個字符的子字串。例如,st:='Brian',則Delete(st,3,2)將變?yōu)锽rn。 

Str(value,st);//將數(shù)值value(整型或?qū)嵭?轉(zhuǎn)換成字符串放在st中。例如,a=2.5E4時,則str(a:10,st)將使st的值為'25000'。 

Val(st,var,code);//把字符串表達式st轉(zhuǎn)換為對應整型或?qū)嵭蛿?shù)值,存放在var中。St必須是一個表示數(shù)值的字符串,并符合數(shù)值常數(shù)的規(guī)則。在轉(zhuǎn)換過程中,如果沒有檢測出錯誤,變量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);//把所有自變量表示出的字符串按所給出的順序連接起來,并返回連接后的值。如果結(jié)果的長度255,將產(chǎn)生運行錯誤。例如,st1:='Brian',st2:='',st3:='Wilfred',則Concat(st1,st2,st3)返回'Brian Wilfred'。 

Length(st);//返回字符串表達式st的長度。例如,st:='Brian',則Length(st)返回值為5。 

Pos(obj,target);//返回字符串obj在目標字符串target的第一次出現(xiàn)的位置,如果target沒有匹配的串,Pos函數(shù)的返回值為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)

A-Z:$41(65)--$5A(90)

0-9:$30(48)--$39(57)

◇[DELPHI]初步判斷程序母語

DELPHI軟件的DOS提示:ThisProgram Must Be Run Under Win32.

VC++軟件的DOS提示:ThisProgram Cannot Be Run In DOS Mode.

◇[DELPHI]操作Cookie

response.cookies("name").domain:='http://www.';

withresponse.cookies.add do

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)<>0 then ... //左鍵

ifGetAsyncKeyState(VK_MButton)<>0 then ... //中鍵

ifGetAsyncKeyState(VK_RButton)<>0 then ... //右鍵

◇[DELPHI]設置窗體的最大顯示

onFormCreate事件

self.width:=screen.width;

self.height:=screen.height;

◇[DELPHI]按鍵接受消息

OnCreate事件中處理:Application.OnMessage:=MyOnMessage;

procedureTForm1.MyOnMessage(var MSG:TMSG;var Handle:Boolean);

begin

ifmsg.message=256 then ... //ANY鍵

ifmsg.message=112 then ... //F1

ifmsg.message=113 then ... //F2

end;

◇[雜類]隱藏共享文件夾

共享效果:可訪問,但不可見(在資源管理、網(wǎng)絡鄰居中)

取共享名為:direction$

訪問://computer/dirction/

◇[JavaScript]Java Script網(wǎng)頁常用效果

網(wǎng)頁60秒定時關閉

關閉窗口

關閉

定時轉(zhuǎn)URL

數(shù)據(jù)源,一個是MQIS,一個是LocalSever,任選一個選后點擊配置按鈕,不知你的SQL7.0

是不是安裝在本地機器上,如果是的話直接進行下一步,如果不是,在服務器一欄中填上

Server,然后進行下一步,填寫登錄ID和密碼(登錄ID,和密碼是在SQL7.0中的用戶選項

中設的)。

第二步,配置BDE:

打開Delphi的BDE,然后點擊MQIS或 LocalServer,就會提示用戶名和密碼,這和

ODBC的用戶名和密碼是一樣的,填上就行了。

第三步,配置程序:

如果用的是TTable,就在TTable的DatabaseName中選擇MQIS或LocalServer,然后在

TableName中選擇Sale就行了,然后將Active改為True,Delphi彈出提示對話,填入用戶

名和密碼。

如果用的是TQuery,在TQuery上點擊右鍵,再擊"SQLBuilder",這是以界面方式配置

SQL語句,或者在TQuery的SQL中填入SQL語句。最后,別忘了將Active改為True。

在運行也可能配置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]關于日期格式分解轉(zhuǎn)換

varyear,month,day:word;now2:Tdatatime;

now2:=date();

decodedate(now2,year,month,day);

lable1.Text:=inttostr(year)+'年'+inttostr(month)+'月'+inttostr(day)+'日'; 

◇[DELPHI]如何判斷當前網(wǎng)絡連接方式

判斷結(jié)果是MODEM、局域網(wǎng)或是代理服務器方式。

useswininet; 

FunctionConnectionKind :boolean; 

var flags:dword; 

begin 

Result :=InternetGetConnectedState(@flags, 0); 

if Resultthen 

begin 

if (flagsand INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM then 

begin 

showmessage('Modem'); 

end; 

if (flagsand INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN then 

begin 

showmessage('LAN'); 

end; 

if (flagsand INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY then 

begin 

showmessage('Proxy'); 

end; 

if (flagsand INTERNET_CONNECTION_MODEM_BUSY)=INTERNET_CONNECTION_MODEM_BUSY then 

begin 

showmessage('ModemBusy'); 

end; 

end; 

end; 

◇[DELPHI]如何判斷字符串是否是有效EMAIL地址

functionIsEMail(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]判斷系統(tǒng)是否連接INTERNET

需要引入URL.DLL中的InetIsOffline函數(shù)。 

函數(shù)申明為:

functionInetIsOffline(Flag: Integer): Boolean; stdcall; external 'URL.DLL'; 

然后就可以調(diào)用函數(shù)判斷系統(tǒng)是否連接到INTERNET

ifInetIsOffline(0) then ShowMessage('not connected!') 

elseShowMessage('connected!'); 

該函數(shù)返回TRUE如果本地系統(tǒng)沒有連接到INTERNET。

附:

大多數(shù)裝有IE或OFFICE97的系統(tǒng)都有此DLL可供調(diào)用。

InetIsOffline

BOOLInetIsOffline(

DWORDdwFlags, 

);

◇[DELPHI]簡單地播放和暫停WAV文件

usesmmsystem;

functionPlayWav(const FileName: string): Boolean; 

begin 

Result :=PlaySound(PChar(FileName), 0, SND_ASYNC); 

end; 

procedureStopWav; 

var 

buffer:array[0..2] of char; 

begin 

buffer[0]:= #0; 

PlaySound(Buffer,0, SND_PURGE); 

end; 

◇[DELPHI]取機器BIOS信息

withMemo1.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]網(wǎng)絡下載文件

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./delphi6.zip, 'c:\kylix.zip') then 

ShowMessage('Downloadsuccesful') 

elseShowMessage('Download unsuccesful') 

◇[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<>nil then result:=StrPas(Hostent^.h_name) else result:=''; 

end; 

◇[DELPHI]取得快捷方式中的連接

functionExeFromLink(const linkname: 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); 

if z >32 then 

Result:=StrPas(ExeName) 

else 

Result:=''; 

StrDispose(FDir); 

StrDispose(FName); 

StrDispose(ExeName); 

end; 

◇[DELPHI]控制TCombobox的自動完成

{'Sorted'property of the TCombobox to true } 

varlastKey: Word; //全局變量

//TCombobox的OnChange事件 

procedureTForm1.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 asTCombobox).ItemIndex := retVal; 

(Sender asTCombobox).SelStart := Length(SearchStr); 

(Sender asTCombobox).SelLength := 

(Length((Senderas TCombobox).Text) - Length(SearchStr)); 

end; //retVal > CB_Err 

end; //lastKey <> VK_BACK 

lastKey :=0; // reset lastKey 

end; 

//TCombobox的OnKeyDown事件

procedureTForm1.AutoCompleteKeyDown(Sender: TObject; var Key: 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

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]如何計算一個目錄的大小 

functionGetDirectorySize(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

whileret=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]安裝程序如何添加到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賦值為顯示在“刪除應用程序列表”中的名稱,如'AimingUninstall one';

給串UninstallString賦值為執(zhí)行的刪除命令,如C:\WIN97\uninst.exe -f"C:\TestPro\aimTest.isu"

◇[DELPHI]截獲WM_QUERYENDSESSION關機消息

type

TForm1 =class(TForm)

procedureWMQueryEndSession(var Message: TWMQueryEndSession); message WM_QUERYENDSESSION;

procedureCMEraseBkgnd(var Message:TWMEraseBkgnd);Message WM_ERASEBKGND;

private

{ Privatedeclarations }

public

{ Publicdeclarations }

end;

procedureTForm1.WMQueryEndSession(var Message: TWMQueryEndSession);

begin

Showmessage('computeris about to shut down');

end;

◇[DELPHI]獲取網(wǎng)上鄰居

proceduregetnethood();//NT做服務器,WIN98上調(diào)試通過。

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;

withnetres[0] do begin

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_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);

// 獲取所有的計算機

mylistitems:=controlcenter.lstcomputer.Items ;

mylistitems.Clear;

for i:=0 toalldomain.Count-1 do

begin

withnetres[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);

iferrcode=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]獲取某一計算機上的共享目錄

proceduregetsharefolder(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

withnetres[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; //獲取根結(jié)點

errcode:=wnetopenenum(RESOURCE_GLOBALNET,RESOURCETYPE_DISK,RESOURCEUSAGE_CONTAINER,@netres[0],enumhandle);

iferrcode=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

withmylistitems do

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] of char; 

begin 

ifGetVolumeInformation('c:\', Buffer, SizeOf(Buffer), SerialNum, a, b, nil, 0)then Label1.Caption := IntToStr(SerialNum^); 

end; 

◇[DELPHI]MEMO的自動翻頁

ProcedureScrollMemo(Memo : TMemo; Direction : char); 

begin 

casedirection of 

'd':begin 

SendMessage(Memo.Handle,{ HWND of the Memo Control } 

WM_VSCROLL,{ Windows Message } 

SB_PAGEDOWN,{ Scroll Command } 

0) { NotUsed } 

end; 

'u' :begin 

SendMessage(Memo.Handle,{ HWND of the Memo Control } 

WM_VSCROLL,{ Windows Message } 

SB_PAGEUP,{ Scroll Command } 

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; var Key: Char);

begin

if Key =#13 then

ifDBGrid1.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]如何安裝控件

安裝方法:

1.對于單個控件,Component-->installcomponent..-->PAS或DCU文件-->install

2.對于帶*.dpk文件的控件包,File-->open(下拉列表框中選*.dpk)-->install即可.

3.對于帶*.dpl文件的控件包,InstallPackages-->Add-->dpl文件名即可。

4.如果以上Install按鈕為失效的話,試試Compile按鈕。

5.是run timelib則在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) = 0 then 

begin 

if (sr.Attrand FileAttrs) = sr.Attr then 

begin 

strfilename:=sr.Name; 

iffileexists(strpth+'\'+strdir+'\'+strfilename) then 

deletefile(strpth+'\'+strdir+'\'+strfilename); 

end; 

whileFindNext(sr) = 0 do 

begin 

if (sr.Attrand FileAttrs) = sr.Attr then 

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; 

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);//行長

◇[DELPHI]讀硬盤序列號 

functionGetDiskSerial(DiskChar: Char): string;

var

SerialNum :pdword;

a, b :dword;

Buffer :array [0..255] of char;

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。 //內(nèi)聯(lián)樣式

Arial//SPAN接受STYLE、CLASS和ID屬性

 

DIV可以包含段落、標題、表格甚至其它部分

 

5。CLASS屬性 

//定義見3。

6。ID屬性 

//定義見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 ]

文本轉(zhuǎn)換:text-transform:[none| capitalize | uppercase | lowercase]

背景顏色:background-color:[<顏色>| transparent]

背景圖象:background-image:[| none]

行高:line-height:[normal | <數(shù)字> | <長度> | <百分比>]

邊框樣式: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.創(chuàng)建部件屬性方法事件

(建立庫單元,繼承為新的類型,添加屬性、方法、事件,注冊部件,建立包文件)

2.消息處理

3.異常處理

4.部件可視

◇[DELPHI]動態(tài)連接庫的裝載

靜態(tài)裝載:procedurename;external 'lib.dll';

動態(tài)裝載:varhandle:Thandle;

handle:=loadlibrary('lib.dll');

ifhandle<>0 then

begin

{dosomething}

freelibrary(handle);

end;

◇[DELPHI]指針變量和地址

varx,y:integer;p:^integer;//指向INTEGER變量的指針

x:=10;//變量賦值

p:=@x;//變量x的地址

y:=p^;//為Y賦值指針P

@@procedure//返回過程變量的內(nèi)存地址

◇[DELPHI]判斷字符是漢字的一個字符

ByteType('你好haha嗎',1)= mbLeadByte//是第一個字符

ByteType('你好haha嗎',2)= mbTrailByte//是第二個字符

ByteType('你好haha嗎',5)= mbSingleByte//不是中文字符

◇[DELPHI]memo的定位操作

memo1.lines.delete(0)//刪除第1行

memo1.selstart:=10//定位10字節(jié)處

◇[DELPHI]獲得雙字節(jié)字符內(nèi)碼

functiongetit(s: string): integer;

begin

Result :=byte(s[1]) * $100 + byte(s[2]);

end;

使用:getit('計')//$bcc6即十進制 48326

◇[DELPHI]調(diào)用ADD數(shù)據(jù)存儲過程

存儲過程如下:

createprocedure addrecord(

record1varchar(10)

record2varchar(20)

)

as

begin

insert intotablename (field1,field2) values(:record1,:record2)

end

執(zhí)行存儲過程:

EXECUTEprocedure addrecord("urrecord1","urrecord2") 

◇[DELPHI]將文件存到blob字段中

functionblobcontenttostring(const filename: 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(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:= GlobalAlloc(GMEM_SHARE or GMEM_ZEROINIT,SizeOf(TDropFiles)+length(FileName)+1);

ifMedium.hGlobal<>0 then begin

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]列舉當前系統(tǒng)運行進程

usesTLHelp32;

procedureTForm1.Button1Click(Sender: TObject);

var lppe:TProcessEntry32;

found :boolean;

Hand :THandle;

begin

Hand :=CreateToolhelp32Snapshot(TH32CS_SNAPALL,0);

found :=Process32First(Hand,lppe);

while founddo

begin

ListBox1.Items.Add(StrPas(lppe.szExeFile));

found :=Process32Next(Hand,lppe);

end;

end;

◇[DELPHI]根據(jù)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.

//調(diào)用(IN urPROJECT)

implementation

functionaddit(f:integer;s:integer):integer;far;external 'project1';//申明

{調(diào)用就是addit(2,4);結(jié)果顯示6}

◇[DELPHI]動態(tài)讀取程序自身大小

functionGesSelfSize: integer;

var

f: file ofbyte;

begin

filemode :=0;

assignfile(f,application.exename);

reset(f);

Result :=filesize(f);//單位是字節(jié)

closefile(f);

end;

◇[DELPHI]讀取BIOS信息

withMemo1.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]動態(tài)建立MSSQL別名

procedureTForm1.Button1Click(Sender: TObject);

var MyList:TStringList;

begin

MyList :=TStringList.Create;

try

with MyListdo

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.MID TYPE SEQUENCER ALIAS NN', '', 0, 0);

MCISendString('PLAYNN FROM 0', '', 0, 0);

MCISendString('CLOSEANIMATION', '', 0, 0);

end;

//停止播放

MCISendString('OPENe:\1.MID TYPE SEQUENCER ALIAS NN', '', 0, 0);

MCISendString('STOPNN', '', 0, 0);

MCISendString('CLOSEANIMATION', '', 0, 0);

◇[DELPHI]接口和類的一個范例代碼

Type{接口和類申明:區(qū)別在于不能在接口中申明數(shù)據(jù)成員、任何非公有的方法、公共方法不使用PUBLIC關鍵字}

Isample=interface//定義Isample接口

functiongetstring:string;

end;

Tsample=class(TInterfacedObject,Isample)

public

functiongetstring:string;

end;

//function定義

functionTsample.getstring:string;

begin

result:='whatshow is ';

end;

//調(diào)用類對象

varsample:Tsample;

begin

sample:=Tsample.create;

showmessage(sample.getstring+'classobject!');

sample.free;

end;

//調(diào)用接口

varsampleinterface:Isample;

sample:Tsample;

begin

sample:=Tsample.create;

sampleInterface:=sample;//Interface的實現(xiàn)必須使用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, ExtendedStyle OR WS_EX_TOOLWINDOW AND NOT WS_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]檢測光驅(qū)符號 

vardrive:char;

cdromID:integer;

begin

fordrive:='d' to 'z' do

begin

cdromID:=GetDriveType(pchar(drive+':\'));

ifcdromID=5 then showmessage('你的光驅(qū)為:'+drive+'盤!');

end;

end;

◇[DELPHI]檢測聲卡

ifauxGetNumDevs()<=0 then showmessage('No soundcard found!') elseshowmessage('Any soundcard found!');

◇[DELPHI]在字符串網(wǎng)格中畫圖

StringGrid.OnDrawCell事件

withStringGrid1.Canvas do 

Draw(Rect.Left,Rect.Top, Image1.Picture.Graphic); 

◇[SQLSERVER]SQL中代替Like語句的另一種寫法

比如查找用戶名包含有"c"的所有用戶,可以用 

usemydatabase 

select *from table1 where username like'%c%" 

下面是完成上面功能的另一種寫法: 

usemydatabase 

select *from table1 where charindex('c',username)>0 

這種方法理論上比上一種方法多了一個判斷語句,即>0,但這個判斷過程是最快的, 我想信80%以上的運算都是花在查找字 

符串及其它的運算上,所以運用charindex函數(shù)也沒什么大不了. 用這種方法也有好處, 那就是對%,|等在不能直接用like 

查找到的字符中可以直接在這charindex中運用,如下: 

usemydatabase 

select *from table1 where charindex('%',username)>0 

也可以寫成: 

usemydatabase 

select *from table1 where charindex(char(37),username)>0 

ASCII的字符即為% 

◇[DELPHI]SQL顯示多數(shù)據(jù)庫/表

SELECTDISTINCT A.bianhao,a.xingming, b.gongzi FROM "jianjie.dbf" a,"gongzi.DBF" b 

WHEREA.bianhao=b.bianhao

◇[DELPHI]RFC(RequestFor Comment)相關

IETF(InternetEngineering Task Force)維護RFC文檔http://www.ietf.cnri.reston.

RFC882:報文頭標結(jié)構(gòu)

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字節(jié)到緩沖區(qū)BUFFER

functionread(var buffer;count:longint):longint;override;

//將緩沖區(qū)BUFFER讀到文件流中

functionwrite(const buffer;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

varmyPlugin = navigator.plugins["Shockwave"];

if(myPlugin)

document.writeln("你已經(jīng)安裝了Shockwave!")

else

document.writeln("你尚未安裝Shockwave!")

 

varmyPlugin = navigator.plugins["Quicktime"];

if(myPlugin)

document.writeln("你已經(jīng)安裝了Quicktime!")

else

document.writeln("你尚未安裝Quicktime!")

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多