◇[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; var windir:array[0..255] of char; getwindowsdirectory(windir,sizeof(windir)); 或者从注册表中读取,位置: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion SystemRoot键,取得如:C:\WINDOWS
◇[DELPHI]在form或其他容器上画线 var x,y:array [0..50] of integer; canvas.pen.color:=clred; canvas.pen.style:=psDash; form1.canvas.moveto(trunc(x),trunc(y)); form1.canvas.lineto(trunc(x[j]),trunc(y[j]));
◇[DELPHI]字符串列表使用 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]处理文件属性 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]取得系统运行的进程名 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]关于键盘常量名 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]判断鼠标按键 if GetAsyncKeyState(VK_LButton)<>0 then ... //左键 if GetAsyncKeyState(VK_MButton)<>0 then ... //中键 if GetAsyncKeyState(VK_RButton)<>0 then ... //右键
◇[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;
◇[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]当前的光驱的盘符 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) 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) xor i xor fkey); end; end;
□◇[DELPHI]向其他应用程序发送模拟键 var h: THandle; begin h := FindWindow(nil, '应用程序标题'); PostMessage(h, WM_KEYDOWN, VK_F9, 0);//发送F9键 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]截获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); 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;
×报错函数 procedure ErrMsg(sMsg:String; sPrompt:String='出错信息');//出错信息显示框 begin Application.MessageBox(PChar(sMsg), PChar(sPrompt), MB_IConERROR or MB_OK) end; ×出错信息 try except on E: Exception do begin ErrMsg(Format('登录[%s]数据库失败,回退操作将失效;'#13#10, [Server]) + E.Message); Result := False; end; end;
×var mytextfile:textfile; begin assignfile(mytextfile,'mytextfile.exe'); reset(mytextfile);//rewrite()创建并打开文件(已有就覆盖),reset()以只读方式打开文件,append()以追加方式打开文件; try //可以加一句while nit eof(mytextfile) do; { //操作文件 for i:=1 to 5 do begin s:='This is line #'; writeln(mytextfile,s,i);//结果被创建的文件中包含 this is line # 1……this is line # 5 //writeln()为往指定文件中写东西,还有readln(mytextfile,s,i)从指定的文件中读数据; end; } finally closefile(mytextfile); end; end;
×edit只能接收数字 procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); begin if ((Key < '0') or (Key > '9')) then Key := Chr(0); end;
×创建路径USES FileCtrl; if not DirectoryExists(ExtractFilePath(paramstr(0)) + 'ElectronicBill\') then CreateDir(ExtractFilePath(paramstr(0)) + 'ElectronicBill\'); fileexists();判断文件是否存在。