先人的DELPHI基础开发技巧

◇[DELPHI]网络邻居复制文件
uses shellapi;
copyfile(pchar('newfile.txt'),pchar('//computername/direction/targer.txt'),false);

◇[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[i]),trunc(y[i]));
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]简单的剪贴板操作
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 (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);//清空

◇[杂类]备份智能ABC输入法词库
windows\system\user.rem
windows\system\tmmr.rem

◇[DELPHI]判断鼠标按键
if GetAsyncKeyState(VK_LButton)<>0 then ... //左键
if GetAsyncKeyState(VK_MButton)<>0 then ... //中键
if GetAsyncKeyState(VK_RButton)<>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秒定时关闭

1<script language="java script"><!--   
2settimeout('window.close();',60000)   
3\--></script>

关闭窗口

1<a href="/" onclick="javascript:window.close();return false;">关闭</a>

定时转URL

1<meta content="40;url=http://www.086net.com" http-equiv="refresh"/>

设为首页

1<a href="#" onclick="this.style.behavior='url(#default#homepage)';this.sethomepage('http://086net.com');">设为首页</a>

收藏本站

1<a href="javascript:window.external.addfavorite('http://086net.com','[未名码头]')">收藏本站</a>

加入频道

1<a href="javascript:window.external.addchannel('http://086net.com')">加入频道</a>

◇[DELPHI]随机产生文本色
randomize;//随机种子
memo1.font.color:=rgb(random(255),random(255),random(255));

◇[DELPHI]DELPHI5 UPDATE升级补丁序列号
1000003185
90X25fx0

◇[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…[<+|->

   1<e|e>&lt;+|-&gt;nnnn]   
   2strtoint (const S:string):longint 将数字字符串转换成整数,字符串可以是十进制或十六进制格式,如果字符串不是一个合法的数字字符串,系统发生ECONVERTERROR异常   
   3strtointdef (const S:string;default:   
   4longint):longint; 将字符串S转换成数字,如果不能将S转换成数字,strtointdef函数返回参数default的值。   
   5strtotime (const S:string):Tdatetime 将字符串S转换成TDATETIME值,S具有HH:MM:SS[AM|PM]格式,实际的格式与系统的时间相关的全局变量有关。   
   6timetostr (time:Tdatetime):string; 将参数TIME转换成字符串。转换结果字符串的格式与系统的时间相关常量的设置有关。 
   7
   8◇[DELPHI]程序不出现在ALT+CTRL+DEL   
   9在implementation后添加声明:   
  10function RegisterServiceProcess(dwProcessID, dwType: Integer): Integer; stdcall; external 'KERNEL32.DLL';   
  11RegisterServiceProcess(GetCurrentProcessID, 1);//隐藏   
  12RegisterServiceProcess(GetCurrentProcessID, 0);//显示   
  13用ALT+DEL+CTRL看不见 
  14
  15◇[DELPHI]程序不出现在任务栏   
  16uses windows   
  17var   
  18Extendedstyle : Integer;   
  19begin   
  20Application.Initialize;   
  21//==============================================================   
  22Extendedstyle := GetWindowLong (Application.Handle, GWL_EXstyle);   
  23SetWindowLong(Application.Handle, GWL_EXstyle, Extendedstyle OR WS_EX_TOOLWINDOW   
  24AND NOT WS_EX_APPWINDOW);   
  25//===============================================================   
  26Application.Createform(Tform1, form1);   
  27Application.Run;   
  28end. 
  29
  30◇[DELPHI]如何判断拨号网络是开还是关   
  31if GetSystemMetrics(SM_NETWORK) AND $01 = $01 then   
  32showmessage('在线!')   
  33else showmessage('不在线!'); 
  34
  35◇[DELPHI]实现IP到域名的转换   
  36function GetDomainName(Ip:string):string;   
  37var   
  38pH:PHostent;   
  39data:twsadata;   
  40ii:dword;   
  41begin   
  42WSAStartup($101, Data);   
  43ii:=inet_addr(pchar(ip));   
  44pH:=gethostbyaddr(@ii,sizeof(ii),PF_INET);   
  45if (ph&lt;&gt;nil) then   
  46result:=pH.h_name   
  47else   
  48result:='';   
  49WSACleanup;   
  50end; 
  51
  52◇[DELPHI]处理“右键菜单”方法   
  53var   
  54reg: TRegistry;   
  55begin   
  56reg := TRegistry.Create;   
  57reg.RootKey:=HKEY_CLASSES_ROOT;   
  58reg.OpenKey('*\shell\check\command', true);   
  59reg.WriteString('', '"' + application.ExeName + '" "%1"');   
  60reg.CloseKey;   
  61reg.OpenKey('*\shell\diary', false);   
  62reg.WriteString('', '操作(&amp;C)');   
  63reg.CloseKey;   
  64reg.Free;   
  65showmessage('DONE!');   
  66end; 
  67
  68◇[DELPHI]发送虚拟键值ctrl V   
  69procedure sendpaste;   
  70begin   
  71keybd_event(VK_Control, MapVirtualKey(VK_Control, 0), 0, 0);   
  72keybd_event(ord('V'), MapVirtualKey(ord('V'), 0), 0, 0);   
  73keybd_event(ord('V'), MapVirtualKey(ord('V'), 0), KEYEVENTF_KEYUP, 0);   
  74keybd_event(VK_Control, MapVirtualKey(VK_Control, 0), KEYEVENTF_KEYUP, 0);   
  75end; 
  76
  77◇[DELPHI]当前的光驱的盘符   
  78procedure getcdrom(var cd:char);   
  79var   
  80str:string;   
  81drivers:integer;   
  82driver:char;   
  83i,temp:integer;   
  84begin   
  85drivers:=getlogicaldrives;   
  86temp:=(1 and drivers);   
  87for i:=0 to 26 do   
  88begin   
  89if temp=1 then   
  90begin   
  91driver:=char(i+integer('a'));   
  92str:=driver+':';   
  93if getdrivetype(pchar(str))=drive_cdrom then   
  94begin   
  95cd:=driver;   
  96exit;   
  97end;   
  98end;   
  99drivers:=(drivers shr 1);   
 100temp:=(1 and drivers);   
 101end;   
 102end; 
 103
 104◇[DELPHI]字符的加密与解密   
 105function cryptstr(const s:string; stype: dword):string;   
 106var   
 107i: integer;   
 108fkey: integer;   
 109begin   
 110result:='';   
 111case stype of   
 1120: setpass;   
 113begin   
 114randomize;   
 115fkey := random($ff);   
 116for i:=1 to length(s) do   
 117result := result+chr( ord(s[i]) xor i xor fkey);   
 118result := result + char(fkey);   
 119end;   
 1201: getpass   
 121begin   
 122fkey := ord(s[length(s)]);   
 123for i:=1 to length(s) - 1 do   
 124result := result+chr( ord(s[i]) xor i xor fkey);   
 125end;   
 126end; 
 127
 128□◇[DELPHI]向其他应用程序发送模拟键   
 129var   
 130h: THandle;   
 131begin   
 132h := FindWindow(nil, '应用程序标题');   
 133PostMessage(h, WM_KEYDOWN, VK_F9, 0);//发送F9键   
 134end; 
 135
 136□◇[DELPHI]DELPHI 支持的DAO数据格式   
 137td.Fields.Append(td.CreateField ('dbBoolean',dbBoolean,0));   
 138td.Fields.Append(td.CreateField ('dbByte',dbByte,0));   
 139td.Fields.Append(td.CreateField ('dbInteger',dbInteger,0));   
 140td.Fields.Append(td.CreateField ('dbLong',dbLong,0));   
 141td.Fields.Append(td.CreateField ('dbCurrency',dbCurrency,0));   
 142td.Fields.Append(td.CreateField ('dbSingle',dbSingle,0));   
 143td.Fields.Append(td.CreateField ('dbDouble',dbDouble,0));   
 144td.Fields.Append(td.CreateField ('dbDate',dbDate,0));   
 145td.Fields.Append(td.CreateField ('dbBinary',dbBinary,0));   
 146td.Fields.Append(td.CreateField ('dbText',dbText,0));   
 147td.Fields.Append(td.CreateField ('dbLongBinary',dbLongBinary,0));   
 148td.Fields.Append(td.CreateField ('dbMemo',dbMemo,0));   
 149td.Fields['ID'].Set_Attributes(dbAutoIncrField);//自增字段 
 150
 151□◇[DELPHI]DELPHI配置MS SQL 7和BDE步骤   
 152第一步,配置ODBC:   
 153先在ODBC 中设数据源,安装过SQL Server7.0 后,ODBC中有一项"系统DSN"应该有两项   
 154数据源,一个是MQIS,一个是LocalSever,任选一个选后点击配置按钮,不知你的SQL7.0   
 155是不是安装在本地机器上,如果是的话直接进行下一步,如果不是,在服务器一栏中填上   
 156Server,然后进行下一步,填写登录ID 和密码(登录ID,和密码是在SQL7.0中的用户选项   
 157中设的)。   
 158第二步,配置BDE:   
 159打开Delphi的BDE,然后点击MQIS 或 LocalServer,就会提示用户名和密码,这和   
 160ODBC的用户名和密码是一样的,填上就行了。   
 161第三步,配置程序:   
 162如果用的是TTable,就在TTable的DatabaseName中选择MQIS 或LocalServer,然后在   
 163TableName中选择Sale就行了,然后将Active改为True,Delphi弹出提示对话,填入用户   
 164名和密码。   
 165如果用的是TQuery,在TQuery上点击右键,再击"SQL Builder",这是以界面方式配置   
 166SQL语句,或者在TQuery的SQL中填入SQL语句。最后,别忘了将Active改为True。   
 167在运行也可能配置TQuery,具体见Delphi帮助。 
 168
 169□◇[DELPHI]得到图像上某一点的RGB值   
 170procedure Tform1.Image1MouseDown(Sender: TObject; Button: TMouseButton;   
 171Shift: TShiftState; X, Y: Integer);   
 172var   
 173red,green,blue:byte ;   
 174i:integer;   
 175begin   
 176i:= image1.Canvas.Pixels[x,y];   
 177Blue:= GetBvalue(i);   
 178Green:= GetGvalue(i):   
 179Red:= GetRvalue(i);   
 180Label1.Caption:=inttostr(Red);   
 181Label2.Caption:=inttostr(Green);   
 182Label3.Caption:=inttostr(Blue);   
 183end; 
 184
 185□◇[DELPHI]关于日期格式分解转换   
 186var year,month,day:word;now2:Tdatatime;   
 187now2:=date();   
 188decodedate(now2,year,month,day);   
 189lable1.Text :=inttostr(year)+'年'+inttostr(month)+'月'+inttostr(day)+'日'; 
 190
 191◇[DELPHI]如何判断当前网络连接方式   
 192判断结果是MODEM、局域网或是代理服务器方式。   
 193uses wininet;   
 194Function ConnectionKind :boolean;   
 195var flags: dword;   
 196begin   
 197Result := InternetGetConnectedState(@flags, 0);   
 198if Result then   
 199begin   
 200if (flags and INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM then   
 201begin   
 202showmessage('Modem');   
 203end;   
 204if (flags and INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN then   
 205begin   
 206showmessage('LAN');   
 207end;   
 208if (flags and INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY then   
 209begin   
 210showmessage('Proxy');   
 211end;   
 212if (flags and INTERNET_CONNECTION_MODEM_BUSY)=INTERNET_CONNECTION_MODEM_BUSY then   
 213begin   
 214showmessage('Modem Busy');   
 215end;   
 216end;   
 217end; 
 218
 219◇[DELPHI]如何判断字符串是否是有效EMAIL地址   
 220function IsEMail(EMail: String): Boolean;   
 221var s: String;ETpos: Integer;   
 222begin   
 223ETpos:= pos( '@' , EMail);   
 224if ETpos &gt; 1 then   
 225begin   
 226s:= copy(EMail,ETpos+1,Length(EMail));   
 227if (pos('.', s) &gt; 1) and (pos('.', s) &lt; length(s)) then   
 228Result:= true else Result:= false;   
 229end   
 230else   
 231Result:= false;   
 232end; 
 233
 234◇[DELPHI]判断系统是否连接INTERNET   
 235需要引入URL.DLL中的InetIsOffline函数。   
 236函数申明为:   
 237function InetIsOffline(Flag: Integer): Boolean; stdcall; external 'URL.DLL';   
 238然后就可以调用函数判断系统是否连接到INTERNET   
 239if InetIsOffline(0) then ShowMessage('not connected!')   
 240else ShowMessage('connected!');   
 241该函数返回TRUE如果本地系统没有连接到INTERNET。   
 242附:   
 243大多数装有IE或OFFICE97的系统都有此DLL可供调用。   
 244InetIsOffline   
 245BOOL InetIsOffline(   
 246DWORD dwFlags,   
 247); 
 248
 249◇[DELPHI]简单地播放和暂停WAV文件   
 250uses mmsystem; 
 251
 252function PlayWav(const FileName: string): Boolean;   
 253begin   
 254Result := PlaySound(PChar(FileName), 0, SND_ASYNC);   
 255end; 
 256
 257procedure StopWav;   
 258var   
 259buffer: array[0..2] of char;   
 260begin   
 261buffer[0] := #0;   
 262PlaySound(Buffer, 0, SND_PURGE);   
 263end; 
 264
 265◇[DELPHI]取机器BIOS信息   
 266with Memo1.Lines do   
 267begin   
 268Add('MainBoardBiosName:'+^I+string(Pchar(Ptr($FE061))));   
 269Add('MainBoardBiosCopyRight:'+^I+string(Pchar(Ptr($FE091))));   
 270Add('MainBoardBiosDate:'+^I+string(Pchar(Ptr($FFFF5))));   
 271Add('MainBoardBiosSerialNo:'+^I+string(Pchar(Ptr($FEC71))));   
 272end; 
 273
 274◇[DELPHI]网络下载文件   
 275uses UrlMon; 
 276
 277function DownloadFile(Source, Dest: string): Boolean;   
 278begin   
 279try   
 280Result := UrlDownloadToFile(nil, PChar(source), PChar(Dest), 0, nil) = 0;   
 281except   
 282Result := False;   
 283end;   
 284end; 
 285
 286if DownloadFile('http://www.borland.com/delphi6.zip, 'c:\kylix.zip') then   
 287ShowMessage('Download succesful')   
 288else ShowMessage('Download unsuccesful') 
 289
 290◇[DELPHI]解析服务器IP地址   
 291uses winsock 
 292
 293function IPAddrToName(IPAddr : String): String;   
 294var   
 295SockAddrIn: TSockAddrIn;   
 296HostEnt: PHostEnt;   
 297WSAData: TWSAData;   
 298begin   
 299WSAStartup($101, WSAData);   
 300SockAddrIn.sin_addr.s_addr:= inet_addr(PChar(IPAddr));   
 301HostEnt:= gethostbyaddr(@SockAddrIn.sin_addr.S_addr, 4, AF_INET);   
 302if HostEnt&lt;&gt;nil then result:=StrPas(Hostent^.h_name) else result:='';   
 303end; 
 304
 305◇[DELPHI]取得快捷方式中的连接   
 306function ExeFromLink(const linkname: string): string;   
 307var   
 308FDir,   
 309FName,   
 310ExeName: PChar;   
 311z: integer;   
 312begin   
 313ExeName:= StrAlloc(MAX_PATH);   
 314FName:= StrAlloc(MAX_PATH);   
 315FDir:= StrAlloc(MAX_PATH);   
 316StrPCopy(FName, ExtractFileName(linkname));   
 317StrPCopy(FDir, ExtractFilePath(linkname));   
 318z:= FindExecutable(FName, FDir, ExeName);   
 319if z &gt; 32 then   
 320Result:= StrPas(ExeName)   
 321else   
 322Result:= '';   
 323StrDispose(FDir);   
 324StrDispose(FName);   
 325StrDispose(ExeName);   
 326end; 
 327
 328◇[DELPHI]控制TCombobox的自动完成   
 329{'Sorted' property of the TCombobox to true }   
 330var lastKey: Word; //全局变量   
 331//TCombobox的OnChange事件   
 332procedure Tform1.AutoCompleteChange(Sender: TObject);   
 333var   
 334SearchStr: string;   
 335retVal: integer;   
 336begin   
 337SearchStr := (Sender as TCombobox).Text;   
 338if lastKey &lt;&gt; VK_BACK then // backspace: VK_BACK or $08   
 339begin   
 340retVal := (Sender as TCombobox).Perform(CB_FINDSTRING, -1, LongInt(PChar(SearchStr)));   
 341if retVal &gt; CB_Err then   
 342begin   
 343(Sender as TCombobox).ItemIndex := retVal;   
 344(Sender as TCombobox).SelStart := Length(SearchStr);   
 345(Sender as TCombobox).SelLength :=   
 346(Length((Sender as TCombobox).Text) - Length(SearchStr));   
 347end; // retVal &gt; CB_Err   
 348end; // lastKey &lt;&gt; VK_BACK   
 349lastKey := 0; // reset lastKey   
 350end;   
 351//TCombobox的onKeyDown事件   
 352procedure Tform1.AutoCompleteKeyDown(Sender: TObject; var Key: Word;   
 353Shift: TShiftState);   
 354begin   
 355lastKey := Key;   
 356end; 
 357
 358◇[DELPHI]如何清空一个目录   
 359function EmptyDirectory(TheDirectory :String ; Recursive : Boolean) :   
 360Boolean;   
 361var   
 362SearchRec : TSearchRec;   
 363Res : Integer;   
 364begin   
 365Result := False;   
 366TheDirectory := NormalDir(TheDirectory);   
 367Res := FindFirst(TheDirectory + '*.*', faAnyFile, SearchRec);   
 368try   
 369while Res = 0 do   
 370begin   
 371if (SearchRec.Name &lt;&gt; '.') and (SearchRec.Name &lt;&gt; '..') then   
 372begin   
 373if ((SearchRec.Attr and faDirectory) &gt; 0) and Recursive   
 374then begin   
 375EmptyDirectory(TheDirectory + SearchRec.Name, True);   
 376RemoveDirectory(PChar(TheDirectory + SearchRec.Name));   
 377end   
 378else begin   
 379DeleteFile(PChar(TheDirectory + SearchRec.Name))   
 380end;   
 381end;   
 382Res := FindNext(SearchRec);   
 383end;   
 384Result := True;   
 385finally   
 386FindClose(SearchRec.FindHandle);   
 387end;   
 388end; 
 389
 390◇[DELPHI]安装程序如何添加到Uninstall列表   
 391操作注册表,如下:   
 3921.在HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall键下建立一个主键,名称任意。   
 393例HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\MyUninstall   
 3942.在HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\MyUnistall下键两个串值,   
 395这两个串值的名称是特定的:DisplayName和UninstallString。   
 3963.给串DisplayName赋值为显示在“删除应用程序列表”中的名称,如'Aiming Uninstall one';   
 397给串UninstallString赋值为执行的删除命令,如 C:\WIN97\uninst.exe -f"C:\TestPro\aimTest.isu" 
 398
 399◇[DELPHI]截获WM_QUERYENDSESSION关机消息   
 400type   
 401Tform1 = class(Tform)   
 402procedure WMQueryEndSession(var Message: TWMQueryEndSession); message WM_QUERYENDSESSION;   
 403procedure CMEraseBkgnd(var Message:TWMEraseBkgnd);Message WM_ERASEBKGND;   
 404private   
 405{ Private declarations }   
 406public   
 407{ Public declarations }   
 408end; 
 409
 410procedure Tform1.WMQueryEndSession(var Message: TWMQueryEndSession);   
 411begin   
 412Showmessage('computer is about to shut down');   
 413end; 
 414
 415◇[DELPHI]获取网上邻居   
 416procedure getnethood();//NT做服务器,WIN98上调试通过。   
 417var   
 418a,i:integer;   
 419errcode:integer;   
 420netres:array[0..1023] of netresource;   
 421enumhandle:thandle;   
 422enumentries:dword;   
 423buffersize:dword;   
 424s:string;   
 425mylistitems:tlistitems;   
 426mylistitem:tlistitem;   
 427alldomain:tstrings;   
 428begin //listcomputer is a listview to list all computers;controlcenter is a form.   
 429alldomain:=tstringlist.Create ;   
 430with netres[0] do begin   
 431dwscope :=RESOURCE_GLOBALNET;   
 432dwtype :=RESOURCETYPE_ANY;   
 433dwdisplaytype :=RESOURCEDISPLAYTYPE_DOMAIN;   
 434dwusage :=RESOURCEUSAGE_CONTAINER;   
 435lplocalname :=nil;   
 436lpremotename :=nil;   
 437lpcomment :=nil;   
 438lpprovider :=nil;   
 439end; // 获取所有的域   
 440errcode:=wnetopenenum(RESOURCE_GLOBALNET,RESOURCETYPE_ANY,RESOURCEUSAGE_CONTAINER,@netres[0],enumhandle);   
 441if errcode=NO_ERROR then begin   
 442enumentries:=1024;   
 443buffersize:=sizeof(netres);   
 444errcode:=wnetenumresource(enumhandle,enumentries,@netres[0],buffersize);   
 445end;   
 446a:=0;   
 447mylistitems :=controlcenter.lstcomputer.Items ;   
 448mylistitems.Clear ;   
 449while (string(netres[a].lpprovider)&lt;&gt;'') and (errcode=NO_ERROR) do   
 450begin   
 451alldomain.Add (netres[a].lpremotename);   
 452a:=a+1;   
 453end;   
 454wnetcloseenum(enumhandle);   
 455// 获取所有的计算机   
 456mylistitems :=controlcenter.lstcomputer.Items ;   
 457mylistitems.Clear ;   
 458for i:=0 to alldomain.Count-1 do   
 459begin   
 460with netres[0] do begin   
 461dwscope :=RESOURCE_GLOBALNET;   
 462dwtype :=RESOURCETYPE_ANY;   
 463dwdisplaytype :=RESOURCEDISPLAYTYPE_SERVER;   
 464dwusage :=RESOURCEUSAGE_CONTAINER;   
 465lplocalname :=nil;   
 466lpremotename :=pchar(alldomain[i]);   
 467lpcomment :=nil;   
 468lpprovider :=nil;   
 469end;   
 470ErrCode:=WNetOpenEnum(RESOURCE_GLOBALNET,RESOURCETYPE_ANY,RESOURCEUSAGE_CONTAINER,@netres[0],EnumHandle);   
 471if errcode=NO_ERROR then   
 472begin   
 473EnumEntries:=1024;   
 474BufferSize:=SizeOf(NetRes);   
 475ErrCode:=WNetEnumResource(EnumHandle,EnumEntries,@NetRes[0],BufferSize);   
 476end;   
 477a:=0;   
 478while (string(netres[a].lpprovider)&lt;&gt;'') and (errcode=NO_ERROR) do   
 479begin   
 480mylistitem :=mylistitems.Add ;   
 481mylistitem.ImageIndex :=0;   
 482mylistitem.Caption :=uppercase(stringreplace(string(NetRes[a].lpremotename),'\\\','',[rfReplaceAll]));   
 483a:=a+1;   
 484end;   
 485wnetcloseenum(enumhandle);   
 486end;   
 487end; 
 488
 489◇[DELPHI]获取某一计算机上的共享目录   
 490procedure getsharefolder(const computername:string);   
 491var   
 492errcode,a:integer;   
 493netres:array[0..1023] of netresource;   
 494enumhandle:thandle;   
 495enumentries,buffersize:dword;   
 496s:string;   
 497mylistitems:tlistitems;   
 498mylistitem:tlistitem;   
 499mystrings:tstringlist;   
 500begin   
 501with netres[0] do begin   
 502dwscope :=RESOURCE_GLOBALNET;   
 503dwtype :=RESOURCETYPE_DISK;   
 504dwdisplaytype :=RESOURCEDISPLAYTYPE_SHARE;   
 505dwusage :=RESOURCEUSAGE_CONTAINER;   
 506lplocalname :=nil;   
 507lpremotename :=pchar(computername);   
 508lpcomment :=nil;   
 509lpprovider :=nil;   
 510end; // 获取根结点   
 511errcode:=wnetopenenum(RESOURCE_GLOBALNET,RESOURCETYPE_DISK,RESOURCEUSAGE_CONTAINER,@netres[0],enumhandle);   
 512if errcode=NO_ERROR then   
 513begin   
 514EnumEntries:=1024;   
 515BufferSize:=SizeOf(NetRes);   
 516ErrCode:=WNetEnumResource(EnumHandle,EnumEntries,@NetRes[0],BufferSize);   
 517end;   
 518wnetcloseenum(enumhandle);   
 519a:=0;   
 520mylistitems:=controlcenter.lstfile.Items ;   
 521mylistitems.Clear ;   
 522while (string(netres[a].lpprovider)&lt;&gt;'') and (errcode=NO_ERROR) do   
 523begin   
 524with mylistitems do   
 525begin   
 526mylistitem:=add;   
 527mylistitem.ImageIndex :=4;   
 528mylistitem.Caption :=extractfilename(netres[a].lpremotename);   
 529end;   
 530a:=a+1;   
 531end;   
 532end; 
 533
 534◇[DELPHI]得到硬盘序列号   
 535var SerialNum : pdword; a, b : dword; Buffer : array [0..255] of char;   
 536begin   
 537if GetVolumeInformation('c:\', Buffer, SizeOf(Buffer), SerialNum, a, b, nil, 0) then Label1.Caption := IntToStr(SerialNum^);   
 538end; 
 539
 540  
 5411.关于MDI主窗体背景新解   
 542在Form中添加Image控件   
 543设BMP图象   
 544name为 IMG_BK   
 545在Foem的Create事件中写入   
 546Self.brush.bitmap:=img_bk.picture.bitmap; 
 547
 5482.在标题栏处画VCL控件(一行解决问题!!!)   
 549在 form 的onpaint 事件中   
 550控件.pointto(getdc(0),left,top); 
 551
 5523 Edit 中只输入数字   
 553SetWindowLong(Edit1.Handle, GWL_STYLE,   
 554GetWindowLong(Edit1.Handle, GWL_STYLE) or   
 555ES_NUMBER);   
 5564.类似MDI方式新解   
 557在要设置child的oncreate方式下写入:   
 558self.parent:='要设置为mainform的Form'; 
 559
 5605\. 屏幕的Refresh(只需一行!)   
 561RedrawWindow(0,nil,0,RDW_ERASE or RDW_INVALIDATE or RDW_ALLCHILDREN);   
 562| |   
 563\--- ----   
 564handle RGN(可刷新局部屏幕)   
 5656.类似DOS下的CLS指令的WINDOWS指令!   
 566paintdesktop(getdc(0)); 
 567
 5687.扩展控件新功能   
 569在编程中 ,我们经常要控制控件的动作,但该控件又没有提供该方法 
 570
 571这时 ,可通过发消息给该控件 ,以达到我们的目的! 
 572
 573如:   
 574button1.perform(wm_keydown,13,0); 
 575
 576listbox1.perform(wm_vscroll,sb_linedown,0); 
 577
 578等等 可少去 重载之苦!!!!! 
 579
 5808.闪烁标题如打印机超时(一行)   
 581form 放一timer 控件 
 582
 583time 事件 中 写入 ; 
 584
 585flashwindow(application.handle,true); 
 586
 587  
 5889.在桌面上加个VCL控件!(不是画的,不可refresh)   
 589windows.setparent(控件.handle,0); 
 590
 591注: 想放哪都行 (如'开始处状态栏') 
 592
 593  
 59410.关于 '类似MDI方式新解(一行就行!!!!)'的修正   
 595windows.setparent(self.handle,'要设置为mainform的Form'); 
 596
 59711 普通Form象MDI中mainform始终在最底层   
 598SetActiveWindow(0);   
 599或 SetwindowPos(...);   
 60012 执行下列语句开始Windows屏幕保护程序   
 601SendMessage(HWND_BROADCAST,WM_SYSCOMMAND,SC_SCREENSAVE,0);   
 60213 button 的 caption 多行显示:   
 603SetWindowLong(Button1.handle, GWL_STYLE,   
 604GetWindowlong(Button1.Handle, GWL_STYLE) or   
 605BS_MULTILINE);   
 606必要时加上 Button1.Invalidate; 
 607
 60814.整死windows98 :)   
 609asm int $19 end 
 610
 611Q: 怎么来改变ListBox的字体呢?就修改其中的一行。 
 612
 613A: 先把ListBox1.Style 设成lbOwnerDrawFixed   
 614然后在 OnDrawItem 事件下写下如下代码 
 615
 616procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;   
 617Rect: TRect; State: TOwnerDrawState);   
 618var   
 619Offset: Integer;   
 620begin   
 621Offset := 2;   
 622with (Control as TListBox).Canvas do begin   
 623FillRect(Rect);   
 624if Index = 2 then begin   
 625Font.Name := 'Fixedsys';   
 626Font.Color := clRed;   
 627Font.Size := 12;   
 628end else begin   
 629Font.Name := 'Arial';   
 630Font.Color := clBlack;   
 631Font.Size := 8;   
 632end;   
 633if odSelected in State then begin   
 634Font.Color := clWhite;   
 635end;   
 636TextOut(Rect.Left + Offset, Rect.Top, (Control as TListBox).Items[Index]);   
 637end;   
 638end; 
 639
 640  
 641Q:怎么在RichEdit里面插入图片? 
 642
 643A: 请到这里来看看会找到答案 
 644
 645http://www.undu.com/Articles/991107c.html 
 646
 647  
 648Q:怎么才能目录呢? 
 649
 650A:我来。 
 651
 652uses ShellAPI; 
 653
 654procedure DeleteFiles(Source: string);   
 655var   
 656FO: TShFileOpStruct;   
 657begin   
 658FillChar(FO,SizeOf(FO),#0);   
 659FO.Wnd := Form1.Handle;   
 660FO.wFunc := FO_DELETE;   
 661FO.pFrom := PChar(Source);   
 662ShFileOperation(FO);   
 663end; 
 664
 665procedure EmptyDirectory(Path: String);   
 666begin   
 667if DirectoryExists(Path) then   
 668begin   
 669DeleteFiles(Path+'\\*');   
 670end   
 671else   
 672ForceDirectories(Path);   
 673end; 
 674
 675Q:如何映射网络驱动器? 
 676
 677比如我要把 \\\Server\sys 映射为F盘。我需要一个函数比如 
 678
 679给出输入参数为 \\\server\sys\home\bruno 给我的返回值是F:\home\bruno 
 680
 681A: 
 682
 683Function UNCToDrive(UNCPath: STring): STring;   
 684var   
 685DriveNum: Integer;   
 686DriveChar: Char;   
 687DriveBits: set of 0..25;   
 688StartSTr,TestStr: STring;   
 689begin   
 690result := UNCPath;   
 691StartSTr := UNCPath;   
 692Integer(DriveBits) := GetLogicalDrives;   
 693for DriveNum := 0 to 25 do   
 694begin   
 695if (DriveNum in DriveBits) then begin   
 696DriveChar := Char(DriveNum + Ord('A'));   
 697TestSTr := ExpandUNCFileName(DriveChar+':\');   
 698If TEstStr &lt;&gt; '' then   
 699If Pos(Uppercase(TestSTr),Uppercase(STartSTr)) &gt; 0 then   
 700begin   
 701Delete(StartSTr,1,Length(TestSTr));   
 702result := DriveChar+':\'+StartSTr;   
 703break;   
 704end;   
 705end;   
 706end;   
 707end; 
 708
 709  
 710Q:我有一些特殊语言的字体来用,它们存储在我的EXE文件里,但是两点。 
 711
 712* 我不想放到font文件夹里   
 713* 我不想从EXE文件里面提取出来 
 714
 715如果可能,请告诉我。 
 716
 717因为,我的字体是自己做的不是windows自带的,我想保护自己的东西。 
 718
 719A:不太可能,必须提取出来。你可以使用这个保护过程来保护你的文件不被修改和删除。 
 720
 721在EXE执行的时候把字体放到临时文件夹里,结束的时候删除它。 
 722
 723function ProtectFile(sFilename : string) : hFile;   
 724var   
 725hf: hFile;   
 726lwHFileSize, lwFilesize: longword;   
 727ofs : TOFStruct;   
 728begin   
 729if FileExists(sFilename) then   
 730begin   
 731hf := OpenFile(pchar(sFilename), ofs, OF_READ or OF_WRITE or OF_SHARE_EXCLUSIVE);   
 732if hf &lt;&gt; 0 then   
 733begin   
 734lwFilesize := GetFileSize(hf, @lwHFileSize);   
 735if LockFile(hf, 0, 0, lwFilesize, lwHFilesize) then   
 736Result := hf else Result := 0;   
 737end   
 738else Result := 0;   
 739end   
 740else Result := 0;   
 741end; 
 742
 743//..   
 744var   
 745ResS: TResourceStream;   
 746TempPath: array [0..MAX_PATH] of Char;   
 747TempDir: string;   
 748begin   
 749GetTempPath(Sizeof(TempPath), TempPath);   
 750TempDir := StrPas(Path);   
 751ResS := TResourceStream.Create(hInstance, 'SOME_FONT', 'RT_FONT');   
 752ResS.SavetoFile(TempDir+'some_font.ttf');   
 753ResS.Free;   
 754AddFontResource(TempDir+'some_font.ttf');   
 755SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);   
 756ProtectFile(TempDir+'some_font.ttf');   
 757end; 
 758
 759  
 760Q:如何得到当前的ProgramFiles得路径? 
 761
 762A:用读写注册表的方法就可以做到。 
 763
 764代码如下: 
 765
 766uses registry; 
 767
 768procedure TForm1.Button1Click(Sender: TObject);   
 769var   
 770reg:TRegistry;   
 771begin   
 772reg:=TRegistry.Create;   
 773reg.RootKey:=HKEY_LOCAL_MACHINE;   
 774if reg.OpenKey('SOFTWARE\Microsoft\Windows\CurrentVersion',false) then   
 775begin   
 776edit1.Text:=reg.ReadString('ProgramFilesDir');   
 777reg.CloseKey;   
 778reg.Free;   
 779end;   
 780end; 
 781
 782  
 783Q:如何在Jpg图像上写上字? 
 784
 785A:这里有个代码。 
 786
 787hmm, here's a sample with help of Bitmap, you can chance the brush style of canvas to bsClear to make the text transparent 
 788
 789  
 790uses   
 791Jpeg; 
 792
 793procedure TForm1.Button1Click(Sender: TObject);   
 794var   
 795Bmp : TBitmap;   
 796Jpg : TJpegImage;   
 797begin   
 798try   
 799Bmp := TBitmap.Create;   
 800Jpg := TjpegImage.Create;   
 801Jpg.LoadFromFile('c:\img.jpg');   
 802Bmp.Assign(Jpg);   
 803Bmp.Canvas.Brush.Style := bsClear;   
 804Bmp.Canvas.Font.Color := clYellow;   
 805Bmp.Canvas.TextOut(10,10,'Hello World');   
 806Jpg.Assign(Bmp);   
 807Jpg.SaveToFile('c:\img2.jpg');   
 808finally   
 809bmp.Free;   
 810jpg.Free;   
 811end;   
 812end; 
 813
 814Q:怎么用delphi修改文件的时间呢? 
 815
 816在windows下,属性里面有三个日起,创建,修改,存储。我怎么来修改啊? 
 817
 818A:Here is the excerpt from the Jedi Code Library. If it is not complete then get the JCL. 
 819
 820type   
 821// indicates the file time to set, used by SetFileTimesHelper and SetDirTimesHelper   
 822TFileTimes = (ftLastAccess, ftLastWrite, ftCreation); 
 823
 824function SetFileTimesHelper(const FileName: string; const DateTime: TDateTime; Times: TFileTimes): Boolean;   
 825var   
 826Handle: THandle;   
 827FileTime: TFileTime;   
 828SystemTime: TSystemTime;   
 829begin   
 830Result := False;   
 831Handle := CreateFile(PChar(FileName), GENERIC_WRITE, FILE_SHARE_READ, nil,   
 832OPEN_EXISTING, 0, 0);   
 833if Handle &lt;&gt; INVALID_HANDLE_VALUE then   
 834try   
 835//SysUtils.DateTimeToSystemTime(DateTimeToLocalDateTime(DateTime), SystemTime);   
 836SysUtils.DateTimeToSystemTime(DateTime, SystemTime);   
 837if Windows.SystemTimeToFileTime(SystemTime, FileTime) then   
 838begin   
 839case Times of   
 840ftLastAccess:   
 841Result := SetFileTime(Handle, nil, @FileTime, nil);   
 842ftLastWrite:   
 843Result := SetFileTime(Handle, nil, nil, @FileTime);   
 844ftCreation:   
 845Result := SetFileTime(Handle, @FileTime, nil, nil);   
 846end;   
 847end;   
 848finally   
 849CloseHandle(Handle);   
 850end;   
 851end; 
 852
 853//-------------------------------------------------------------------------------------------------- 
 854
 855function SetFileLastAccess(const FileName: string; const DateTime: TDateTime): Boolean;   
 856begin   
 857Result := SetFileTimesHelper(FileName, DateTime, ftLastAccess);   
 858end; 
 859
 860//-------------------------------------------------------------------------------------------------- 
 861
 862function SetFileLastWrite(const FileName: string; const DateTime: TDateTime): Boolean;   
 863begin   
 864Result := SetFileTimesHelper(FileName, DateTime, ftLastWrite);   
 865end; 
 866
 867//-------------------------------------------------------------------------------------------------- 
 868
 869function SetFileCreation(const FileName: string; const DateTime: TDateTime): Boolean;   
 870begin   
 871Result := SetFileTimesHelper(FileName, DateTime, ftCreation);   
 872end; 
 873
 874  
 875google上的有关delphi得网址: 
 876
 877http://directory.google.com/Top/Computers/Programming/Languages/Delphi/?tc=1 
 878
 879yahoo上有关delphi得网址 
 880
 881http://dir.yahoo.com/Computers_and_Internet/Programming_and_Development/Languages/Delphi/ 
 882
 883  
 884删掉程序自己的exe文件   
 885procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);   
 886var   
 887F:TextFile;   
 888begin   
 889AssignFile(F,'delself.bat');   
 890Rewrite(F);{F为TextFile类型}   
 891WriteLn(F,'del '+ExtractFileName(Application.ExeName));   
 892WriteLn(F,'del %0'); //删除自己delself.bat   
 893CloseFile(F);   
 894WinExec('delself.bat',SW_HIDE);   
 895end; 
 896
 897  
 898if ord(s[9])&gt;128 then   
 899ShowMessage('该位置字符是汉字');   
 900汉字是双字节的   
 901更改系统时间格式: 
 902
 903var   
 904str: string;   
 905begin   
 906str := 'yyyy-mm-dd';   
 907if SetLocaleInfoa(LOCALE_SYSTEM_DEFAULT, LOCALE_SLONGDATE, PChar(str)) then   
 908begin   
 909showmessage('更改日期格式成功');   
 910end;   
 911end; 
 912
 913休息一分钟:   
 914var   
 915I:integer;   
 916begin   
 917i:=gettickcount;   
 918while (Gettickcount-i)&lt;=10000 do   
 919application.ProcessMessages;//保证消息循环   
 920end; 
 921
 922  
 923取主文件名:   
 924function retuFileName(const FileName: string): string;   
 925var   
 926I: Integer;   
 927begin   
 928I := LastDelimiter('.', FileName);   
 929Result := Copy(FileName, 1, i-1); 
 930
 931end; 
 932
 933(1).按下ctrl和其它键之后发生一事件。   
 934procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;   
 935Shift: TShiftState);   
 936begin   
 937if (ssCtrl in Shift) and (key =67) then   
 938showmessage('keydown Ctrl+C');   
 939end;   
 940(2).Dbgrid中用Enter键代替Tab键.   
 941procedure TForm1.DBGrid1KeyPress(Sender: TObject; var Key: Char);   
 942begin   
 943if Key = #13 then   
 944if ActiveControl = DBGrid1 then   
 945begin   
 946TDBGrid(ActiveControl).SelectedIndex := TDBGrid(ActiveControl).SelectedIndex + 1;   
 947Key := #0;   
 948end;   
 949end;   
 950(3).Dbgrid中选择多行发生一事件。   
 951procedure TForm1.Button1Click(Sender: TObject);   
 952var   
 953i:integer;   
 954bookmarklist:Tbookmarklist;   
 955bookmark:tbookmarkstr;   
 956begin   
 957bookmark:=adoquery1.Bookmark;   
 958bookmarklist:=dbgrid1.SelectedRows;   
 959try   
 960begin   
 961for i:=0 to bookmarklist.Count-1 do   
 962begin   
 963adoquery1.Bookmark:=bookmarklist[i];   
 964with adoquery1 do   
 965begin   
 966edit;   
 967fieldbyname('mdg').AsString:=edit2.Text;   
 968post;   
 969end;   
 970end;   
 971end;   
 972finally   
 973adoquery1.Bookmark:=bookmark;   
 974end;   
 975end;   
 976(4).Form的一个出现效果。   
 977procedure TForm1.Button1Click(Sender: TObject);   
 978var   
 979r:thandle;   
 980i:integer;   
 981begin   
 982for i:=1 to trunc(width/1.414) do   
 983begin   
 984r:=CreateEllipticRgn(trunc(width/2)-i,trunc(height/2)-i,trunc(width/2)+i,trunc(height/2)+i);   
 985SetWindowRgn(handle,r,true);   
 986Application.ProcessMessages;   
 987sleep(1);   
 988end;   
 989end;   
 990(5).用Enter代替Tab在编辑框中移动隹点。   
 991procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);   
 992begin   
 993if key=#13 then   
 994begin   
 995if not (Activecontrol is Tmemo) then   
 996begin   
 997key:=#0;   
 998keybd_event(vk_tab,mapvirtualkey(vk_tab,0),0,0);   
 999end;   
1000end;   
1001end;   
1002(6).Progressbar加上色彩。   
1003const   
1004{$EXTERNALSYM PBS_MARQUEE}   
1005PBS_MARQUEE = 08;   
1006var   
1007Form1: TForm1;   
1008implementation   
1009{$R *.dfm}   
1010uses   
1011CommCtrl;   
1012procedure TForm1.Button1Click(Sender: TObject);   
1013begin   
1014// Set the Background color to teal   
1015Progressbar1.Brush.Color := clTeal;   
1016// Set bar color to yellow   
1017SendMessage(ProgressBar1.Handle, PBM_SETBARCOLOR, 0, clYellow);   
1018end;   
1019(7).住点移动时编辑框色彩不同。   
1020procedure TForm1.Edit1Enter(Sender: TObject);   
1021begin   
1022(sender as tedit).Color:=clred;   
1023end;   
1024procedure TForm1.Edit1Exit(Sender: TObject);   
1025begin   
1026(sender as tedit).Color:=clwhite;   
1027end;   
1028(8).备份和恢复   
1029procedure TForm1.Button1Click(Sender: TObject);   
1030begin   
1031if OpenDialog1.Execute then   
1032begin   
1033try   
1034adoconnection1.Connected:=False;   
1035adoconnection1.ConnectionString:='Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=master;Data Source=FRIEND-YOFZKSCO;'+   
1036'Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=FRIEND-YOFZKSCO;Use Encryption for Data=False;Tag with column collation when possible=False';   
1037adoconnection1.Connected:=True;   
1038with adoQuery1 do   
1039begin   
1040Close;   
1041SQL.Clear;   
1042SQL.Add('Backup DataBase sfa to disk ='''+opendialog1.FileName+'''');   
1043ExecSQL;   
1044end;   
1045except   
1046ShowMessage('±?·Y꧰ü');   
1047Exit;   
1048end;   
1049end;   
1050Application.MessageBox('1§?2?ú£?êy?Y±?·Y3é1|','ìáê?',MB_OK + MB_ICONINFORMATION);   
1051end;   
1052procedure TForm1.Button2Click(Sender: TObject);   
1053begin   
1054if OpenDialog1.Execute then   
1055begin   
1056try   
1057adoconnection1.Connected:=false;   
1058adoconnection1.ConnectionString:='Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=master;Data Source=FRIEND-YOFZKSCO;'+   
1059'Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=FRIEND-YOFZKSCO;Use Encryption for Data=False;Tag with column collation when possible=False';   
1060adoconnection1.Connected:=true;   
1061with adoQuery1 do   
1062begin   
1063Close;   
1064SQL.Clear;   
1065SQL.Add('Restore DataBase sfa from disk ='''+opendialog1.FileName+'''');   
1066ExecSQL;   
1067end;   
1068except   
1069ShowMessage('???′꧰ü');   
1070Exit;   
1071end;   
1072end;   
1073Application.MessageBox('1§?2?ú£?êy?Y???′3é1|','ìáê?',MB_OK + MB_ICONINFORMATION);   
1074end; 
1075
1076  
1077(9).查找局域网上的sqlserver报务器。   
1078uses Comobj;   
1079procedure TForm1.Button1Click(Sender: TObject);   
1080var   
1081SQLServer:Variant;   
1082ServerList:Variant;   
1083i,nServers:integer;   
1084sRetValue:String;   
1085begin   
1086SQLServer := CreateOleObject('SQLDMO.Application');   
1087ServerList:= SQLServer.ListAvailableSQLServers;   
1088nServers:=ServerList.Count;   
1089for i := 1 to nservers do   
1090ListBox1.Items.Add(ServerList.Item(i));   
1091SQLServer:=NULL;   
1092serverList:=NULL;   
1093end;   
1094(10).窗体打开时的淡入效果。   
1095procedure TForm1.FormCreate(Sender: TObject);   
1096begin   
1097AnimateWindow (Handle, 400, AW_CENTER);   
1098end;   
1099(11).动态创建窗体。   
1100procedure TForm1.Button1Click(Sender: TObject);   
1101begin   
1102try   
1103form2:=Tform2.Create(self);   
1104form2.ShowModal;   
1105finally   
1106form2.Free;   
1107end;   
1108end;   
1109procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);   
1110begin   
1111action:=cafree;   
1112end;   
1113procedure TForm1.FormDestroy(Sender: TObject);   
1114begin   
1115form1:=nil;   
1116end;   
1117(12).复制文件。   
1118procedure TForm1.Button1Click(Sender: TObject);   
1119begin   
1120try   
1121copyfileA(pchar('C:\AAA.txt'),pchar('D:\AAA.txt'),false);   
1122except   
1123showmessage('sfdsdf');   
1124end;   
1125end;   
1126(13).复制文件夹。   
1127uses shellAPI;   
1128procedure TForm1.Button1Click(Sender: TObject);   
1129var   
1130lpFileOp: TSHFileOpStruct;   
1131begin   
1132with lpFileOp do   
1133begin   
1134Wnd:=Self.Handle;   
1135wfunc:=FO_COPY;   
1136pFrom:=pchar('C:\AAA');   
1137pTo:=pchar('D:\AAA');   
1138fFlags:=FOF_ALLOWUNDO;   
1139hNameMappings:=nil;   
1140lpszProgressTitle:=nil;   
1141fAnyOperationsAborted:=True;   
1142end;   
1143if SHFileOperation(lpFileOp)&lt;&gt;0 then   
1144ShowMessage('删除失败');   
1145end;   
1146(14).改变Dbgrid的选定色。   
1147procedure TForm1.DBGrid1DrawDataCell(Sender: TObject; const Rect: TRect;   
1148Field: TField; State: TGridDrawState);   
1149begin   
1150if gdSelected in state then   
1151SetBkColor(dbgrid1.canvas.handle,clgreen)   
1152else   
1153setbkcolor(dbgrid1.canvas.handle,clwhite);   
1154dbgrid1.Canvas.TextRect(rect,0,0,field.AsString);   
1155dbgrid1.Canvas.Textout(rect.Left,rect.Top,field.AsString);   
1156end;   
1157(15).检测系统是否已安装了ADO。   
1158uses registry;   
1159function Tform1.ADOInstalled:Boolean;   
1160var   
1161r:TRegistry;   
1162s:string;   
1163begin   
1164r := TRegistry.create;   
1165try   
1166with r do   
1167begin   
1168RootKey := HKEY_CLASSES_ROOT;   
1169OpenKey( '\ADODB.Connection\CurVer', false );   
1170s := ReadString('');   
1171if s &lt;&gt; '' then Result := True   
1172else Result := False;   
1173CloseKey;   
1174end;   
1175finally   
1176r.free;   
1177end;   
1178end;   
1179procedure TForm1.Button1Click(Sender: TObject);   
1180begin   
1181if ADOInstalled then showmessage('this computer has installed ADO');   
1182end;   
1183(16).取利主机的ip地址。   
1184uses winsock;   
1185procedure TForm1.Button1Click(Sender: TObject);   
1186var   
1187IP:string;   
1188IPstr:String;   
1189buffer:array[1..32] of char;   
1190i:integer;   
1191WSData:TWSAdata;   
1192Host:PHostEnt;   
1193begin   
1194if WSAstartup(2,WSData)&lt;&gt;0 then   
1195begin   
1196showmessage('WS2_32.DLL3?ê??ˉ꧰ü.');   
1197exit;   
1198end;   
1199try   
1200if GetHostname(@buffer[1],32)&lt;&gt;0 then   
1201begin   
1202showmessage('??óDμ?μ??÷?ú??.');   
1203exit;   
1204end;   
1205except   
1206showmessage('??óD3é1|·μ???÷?ú??');   
1207exit;   
1208end;   
1209Host:=GetHostbyname(@buffer[1]);   
1210if Host=nil then   
1211begin   
1212showmessage('IPμ??·?a??.');   
1213exit;   
1214end   
1215else   
1216begin   
1217edit2.Text:=Host.h_name;   
1218edit3.Text:=chr(host.h_addrtype+64);   
1219for i:=1 to 4 do   
1220begin   
1221IP:=inttostr(ord(host.h_addr^[i-1]));   
1222if i&lt;4 then   
1223ipstr:=ipstr+IP+'.'   
1224else   
1225edit1.Text:=ipstr+ip;   
1226end;   
1227end;   
1228WSACleanup;   
1229end;   
1230(17).取得计算机名。   
1231function tform1.get_name:string;   
1232var ComputerName: PChar; size: DWord;   
1233begin   
1234GetMem(ComputerName,255);   
1235size:=255;   
1236if GetComputerName(ComputerName,size)=False then   
1237result:=''   
1238else   
1239result:=ComputerName;   
1240FreeMem(ComputerName);   
1241end;   
1242procedure TForm1.Button1Click(Sender: TObject);   
1243begin   
1244label1.Caption:=get_name;   
1245end; 
1246
1247  
1248(18).取得硬盘序列号。   
1249function tform1.GetHDSerialNumber: LongInt;   
1250{$IFDEF WIN32}   
1251var   
1252pdw : pDWord;   
1253mc, fl : dword;   
1254{$ENDIF}   
1255begin   
1256{$IfDef WIN32}   
1257New(pdw);   
1258GetVolumeInformation('c:\',nil,0,pdw,mc,fl,nil,0);   
1259Result := pdw^;   
1260dispose(pdw);   
1261{$ELSE}   
1262Result := GetWinFlags;   
1263{$ENDIF}   
1264end;   
1265procedure TForm1.Button1Click(Sender: TObject);   
1266begin   
1267edit1.Text:=inttostr(gethdserialnumber);   
1268end;   
1269(19).限定光标移动范围。   
1270procedure TForm1.Button1Click(Sender: TObject);   
1271var   
1272rect1:trect;   
1273begin   
1274rect1:=button2.BoundsRect;   
1275mapwindowpoints(handle,0,rect1,2);   
1276clipcursor(@rect1);   
1277end;   
1278procedure TForm1.Button2Click(Sender: TObject);   
1279var   
1280screenrect:trect;   
1281begin   
1282screenrect:=rect(0,0,screen.Width,screen.Height);   
1283clipcursor(@screenrect);   
1284end;   
1285(20).限制edit框只能输入数字。   
1286procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);   
1287begin   
1288if not (key in ['0'..'9','.',#8]) then   
1289begin   
1290key:=#0;   
1291Messagebeep(0);   
1292end;   
1293end;   
1294(21).dbgrid中根据任一条件某一格变色。   
1295procedure TForm_main.DBGridEh1DrawColumnCell(Sender: TObject;   
1296const Rect: TRect; DataCol: Integer; Column: TColumnEh;   
1297State: TGridDrawState);   
1298begin   
1299if (trim(DataModule1.ADOQuery1.FieldByName('dczt').AsString)='OK') then   
1300begin   
1301if datacol=6 then   
1302begin   
1303DbGrideh1.Canvas.Brush.Color:=clGradientActiveCaption;   
1304DbGrideh1.DefaultDrawColumnCell(Rect,datacol,column,state);   
1305end;   
1306end;   
1307end;   
1308(22).打开word文件。   
1309procedure TfjfsglForm.SpeedButton4Click(Sender: TObject);   
1310var   
1311MSWord: Variant;   
1312str:string;   
1313begin   
1314if trim(DataModule1.adoquery27.fieldbyname('fjmc').asstring)&lt;&gt;'' then</e|e>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus