Delphi常用代碼彙總

◇[DELPHI]產生鼠標拖動效果
通過MouseMove事件、DragOver事件、EndDrag事件實現,例如在PANEL上的LABEL:
var xpanel,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目錄
uses shellapi;
getwindowsdirectory(windir,sizeof(windir));
或者從註冊表中讀取,位置:
HKEY_LOCAL_MACHINE/Software/Microsoft/Windows/CurrentVersion
SystemRoot鍵,取得如:C:/WINDOWS

trunc()

◇[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 (attr and faReadonly)=faReadonly then ... //只讀
if (attr and faSysfile)=faSysfile then ... //系統
if (attr and faArchive)=faArchive then ... //存檔
if (attr and faHidden)=faHidden then ... //隱藏

◇[DELPHI]執行程序外文件
WINEXEC//調用可執行文件
winexec('command.com /c copy *.* c:/',SW_Normal);
winexec('start abc.txt');
ShellExecute或ShellExecuteEx//啓動文件關聯程序
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]取得系統運行的進程名
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]關於彙編的嵌入
Asm End;
可以任意修改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)返回'Brian Wilfred'。
Length(st);//返回字符串表達式st的長度。例如,st:='Brian',則Length(st)返回值爲5。
Pos(obj,target);//返回字符串obj在目標字符串target的第一次出現的位置,如果target沒有匹配的串,Pos函數的返回值爲0。例如,target:='Brian Wilfred',則Pos('Wil',target)的返回值是7,Pos('hurbet',target)的返回值是0。

◇[DELPHI]關於處理註冊表
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]關於鍵盤常量名
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提示:This Program Must Be Run Under Win32.
VC++軟件的DOS提示:This Program Cannot Be Run In DOS Mode.

◇[DELPHI]操作Cookie
response.cookies("name").domain:='http://www.086net.com';
with response.cookies.add do
begin
name:='username';
value:='username';
end

◇[DELPHI]增加到文檔菜單連接
uses shellapi,shlOBJ;
shAddToRecentDocs(shArd_path,pchar(filepath));//增加連接
shAddToRecentDocs(shArd_path,nil);//清空

◇[DELPHI]判斷鼠標按鍵
if GetAsyncKeyState(VK_L(M,R)Button)<>0 then ... //左鍵

◇[DELPHI]設置窗體的最大顯示
onformCreate事件
self.width:=screen.width;
self.height:=screen.height;

◇[DELPHI]按鍵接受消息
OnCreate事件中處理:Application.OnMessage:=MyOnMessage;
procedure Tform1.MyOnMessage(var MSG:TMSG;var Handle:Boolean);
begin
if msg.message=256 then ... //ANY鍵
if msg.message=112 then ... //F1
if msg.message=113 then ... //F2
end;

◇[雜類]隱藏共享文件夾
共享效果:可訪問,但不可見(在資源管理、網絡鄰居中)
取共享名爲:direction$
訪問://computer/dirction/

◇[Java Script]Java Script網頁常用效果
網頁60秒定時關閉
<script language="java script"><!--
settimeout('window.close();',60000)
--></script>
關閉窗口
<a href="/" οnclick="javascript:window.close();return false;">關閉</a>
定時轉URL
<meta http-equiv="refresh" content="40;url=
http://www.086net.com">
設爲首頁
<a οnclick="this.style.behavior='url(#default#homepage)';this.sethomepage('http://086net.com');"href="#">設爲首頁</a>
收藏本站
<a href="javascript:window.external.addfavorite('http://086net.com','[未名碼頭]')">收藏本站</a>
加入頻道
<a href="javascript:window.external.addchannel('http://086net.com')">加入頻道</a>

◇[DELPHI]隨機產生文本色
randomize;//隨機種子
memo1.font.color:=rgb(random(255),random(255),random(255));

◇[DELPHI]文件名的非法字符過濾
for i:=1 to length(s) do
if s[i] in ['/','/',':','*','?','<','>','|'] then

◇[DELPHI]轉換函數的定義及說明
datetimetofiledate (datetime:Tdatetime):longint; 將Tdatetime格式的日期時間值轉換成DOS格式的日期時間值
datetimetostr (datetime:Tdatetime):string; 將Tdatatime格式變量轉換成字符串,如果datetime參數不包含日期值,返回字符串日期顯示成爲00/00/00,如果datetime參數中沒有時間值,返回字符串中的時間部分顯示成爲00:00:00 AM
datetimetostring (var result string;
const format:string;
datetime:Tdatetime); 根據給定的格式字符串轉換時間和日期值,result爲結果字符串,format爲轉換格式字符串,datetime爲日期時間值
datetostr (date:Tdatetime) 使用shortdateformat全局變量定義的格式字符串將date參數轉換成對應的字符串
floattodecimal (var result:Tfloatrec;value:
extended;precision,decimals:
integer); 將浮點數轉換成十進制表示
floattostr (value:extended):string 將浮點數value轉換成字符串格式,該轉換使用普通數字格式,轉換的有效位數爲15位。
floattotext (buffer:pchar;value:extended;
format:Tfloatformat;precision,
digits:integer):integer; 用給定的格式、精度和小數將浮點值value轉換成十進制表示形式,轉換結果存放於buffer參數中,函數返回值爲存儲到buffer中的字符位數,buffer是非0結果的字符串緩衝區。
floattotextfmt (buffer:pchar;value:extended;
format:pchar):integer 用給定的格式將浮點值value轉換成十進制表示形式,轉換結果存放於buffer參數中,函數返回值爲存儲到buffer中的字符位數。
inttohex (value:longint;digits:integer):
string; 將給定的數值value轉換成十六進制的字符串。參數digits給出轉換結果字符串包含的數字位數。
inttostr (value:longint):string 將整數轉換成十進制形式字符串
strtodate (const S:string):Tdatetime 將字符串轉換成日期值,S必須包含一個合法的格式日期的字符串。
strtodatetime (const S:string):Tdatetime 將字符串S轉換成日期時間格式,S必須具有MM/DD/YY HH:MM:SS[AM|PM]格式,其中日期和時間分隔符與系統時期時間常量設置相關。如果沒有指定AM或PM信息,表示使用24小時制。
strtofloat (const S:string):extended; 將給定的字符串轉換成浮點數,字符串具有如下格式:
[+|-]nnn…[.]nnn…[<+|-><E|e><+|->nnnn]
strtoint (const S:string):longint 將數字字符串轉換成整數,字符串可以是十進制或十六進制格式,如果字符串不是一個合法的數字字符串,系統發生ECONVERTERROR異常
strtointdef (const S:string;default:
longint):longint; 將字符串S轉換成數字,如果不能將S轉換成數字,strtointdef函數返回參數default的值。
strtotime (const S:string):Tdatetime 將字符串S轉換成TDATETIME值,S具有HH:MM:SS[AM|PM]格式,實際的格式與系統的時間相關的全局變量有關。
timetostr (time:Tdatetime):string; 將參數TIME轉換成字符串。轉換結果字符串的格式與系統的時間相關常量的設置有關。

◇[DELPHI]程序不出現在ALT+CTRL+DEL
在implementation後添加聲明:
function RegisterServiceProcess(dwProcessID, dwType: Integer): Integer; stdcall; external 'KERNEL32.DLL';
RegisterServiceProcess(GetCurrentProcessID, 1);//隱藏
RegisterServiceProcess(GetCurrentProcessID, 0);//顯示
用ALT+DEL+CTRL看不見

◇[DELPHI]程序不出現在任務欄
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]如何判斷撥號網絡是開還是關
if GetSystemMetrics(SM_NETWORK) AND $01 = $01 then
showmessage('在線!')
else showmessage('不在線!');

◇[DELPHI]實現IP到域名的轉換
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]處理“右鍵菜單”方法
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('', '操作(&C)');
reg.CloseKey;
reg.Free;
showmessage('DONE!');
end;

◇[DELPHI]發送虛擬鍵值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]當前的光驅的盤符
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]字符的加密與解密
function cryptstr(const s:string; stype: dword):string;
var
i: integer;
fkey: integer;
begin
result:='';
case stype 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]向其他應用程序發送模擬鍵
var
h: THandle;
begin
h := FindWindow(nil, '應用程序標題');
PostMessage(h, WM_KEYDOWN, VK_F9, 0);//發送F9鍵
end;

□◇[DELPHI]DELPHI 支持的DAO數據格式
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);//自增字段

□◇[DELPHI]DELPHI配置MS SQL 7和BDE步驟
第一步,配置ODBC:
先在ODBC 中設數據源,安裝過SQL Server7.0 後,ODBC中有一項"系統DSN"應該有兩項
數據源,一個是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上點擊右鍵,再擊"SQL Builder",這是以界面方式配置
SQL語句,或者在TQuery的SQL中填入SQL語句。最後,別忘了將Active改爲True。
在運行也可能配置TQuery,具體見Delphi幫助。

□◇[DELPHI]得到圖像上某一點的RGB值
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]關於日期格式分解轉換
var year,month,day:word;now2:Tdatatime;
now2:=date();
decodedate(now2,year,month,day);
lable1.Text :=inttostr(year)+'年'+inttostr(month)+'月'+inttostr(day)+'日';

◇[DELPHI]如何判斷當前網絡連接方式
判斷結果是MODEM、局域網或是代理服務器方式。
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]如何判斷字符串是否是有效EMAIL地址
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]判斷系統是否連接INTERNET
需要引入URL.DLL中的InetIsOffline函數。
函數申明爲:
function InetIsOffline(Flag: Integer): Boolean; stdcall; external 'URL.DLL';
然後就可以調用函數判斷系統是否連接到INTERNET
if InetIsOffline(0) then ShowMessage('not connected!')
else ShowMessage('connected!');
該函數返回TRUE如果本地系統沒有連接到INTERNET。
附:
大多數裝有IE或OFFICE97的系統都有此DLL可供調用。
InetIsOffline
BOOL InetIsOffline(
DWORD dwFlags,
);

◇[DELPHI]簡單地播放和暫停WAV文件
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]取機器BIOS信息
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]網絡下載文件
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]解析服務器IP地址
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]取得快捷方式中的連接
function ExeFromLink(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 }
var lastKey: Word; //全局變量
//TCombobox的OnChange事件
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;
//TCombobox的onKeyDown事件
procedure Tform1.AutoCompleteKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
lastKey := Key;
end;

◇[DELPHI]如何清空一個目錄
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]安裝程序如何添加到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賦值爲顯示在“刪除應用程序列表”中的名稱,如'Aiming Uninstall one';
給串UninstallString賦值爲執行的刪除命令,如 C:/WIN97/uninst.exe -f"C:/TestPro/aimTest.isu"

◇[DELPHI]截獲WM_QUERYENDSESSION關機消息
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]獲取網上鄰居
procedure getnethood();//NT做服務器,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; // 獲取所有的域
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);
// 獲取所有的計算機
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]獲取某一計算機上的共享目錄
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; // 獲取根結點
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]得到硬盤序列號
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;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章