先人的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]文本编辑相关
checkbox1.checked:=not checkbox1.checked;
if checkbox1.checked then richedit1.font.style:=richedit1.font.style+[fsBold] else richedit1.font.style:=richedit1.font.style-[fsBold]//粗体
if checkbox1.checked then richedit1.font.style:=richedit1.font.style+[fsItalic] else richedit1.font.style:=richedit1.font.style-[fsItalic]//斜体
if checkbox1.checked then richedit1.font.style:=richedit1.font.style+[fsUnderline] else richedit1.font.style:=richedit1.font.style-[fsUnderline]//下划线
memo1.alignment:=taLeftJustify;//居左
memo1.alignment:=taRightJustify;//居右
memo1.alignment:=taCenter;//居中
◇[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><+|->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<>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('', '操作(&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 > 1 then
225begin
226s:= copy(EMail,ETpos+1,Length(EMail));
227if (pos('.', s) > 1) and (pos('.', s) < 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<>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 > 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 <> VK_BACK then // backspace: VK_BACK or $08
339begin
340retVal := (Sender as TCombobox).Perform(CB_FINDSTRING, -1, LongInt(PChar(SearchStr)));
341if retVal > 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 > CB_Err
348end; // lastKey <> 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 <> '.') and (SearchRec.Name <> '..') then
372begin
373if ((SearchRec.Attr and faDirectory) > 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]如何计算一个目录的大小
391function GetDirectorySize(const ADirectory: string): Integer;
392var
393Dir: TSearchRec;
394Ret: integer;
395Path: string;
396begin
397Result := 0;
398Path := ExtractFilePath(ADirectory);
399Ret := Sysutils.FindFirst(ADirectory, faAnyFile, Dir);
400if Ret <> NO_ERROR then exit;
401try
402while ret=NO_ERROR do
403begin
404inc(Result, Dir.Size);
405if (Dir.Attr in [faDirectory]) and (Dir.Name[1] <> '.') then
406Inc(Result, GetDirectorySize(Path + Dir.Name + '\\*.*'));
407Ret := Sysutils.FindNext(Dir);
408end;
409finally
410Sysutils.FindClose(Dir);
411end;
412end;
413
414◇[DELPHI]安装程序如何添加到Uninstall列表
415操作注册表,如下:
4161.在HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall键下建立一个主键,名称任意。
417例HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\MyUninstall
4182.在HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\MyUnistall下键两个串值,
419这两个串值的名称是特定的:DisplayName和UninstallString。
4203.给串DisplayName赋值为显示在“删除应用程序列表”中的名称,如'Aiming Uninstall one';
421给串UninstallString赋值为执行的删除命令,如 C:\WIN97\uninst.exe -f"C:\TestPro\aimTest.isu"
422
423◇[DELPHI]截获WM_QUERYENDSESSION关机消息
424type
425TForm1 = class(TForm)
426procedure WMQueryEndSession(var Message: TWMQueryEndSession); message WM_QUERYENDSESSION;
427procedure CMEraseBkgnd(var Message:TWMEraseBkgnd);Message WM_ERASEBKGND;
428private
429{ Private declarations }
430public
431{ Public declarations }
432end;
433
434procedure TForm1.WMQueryEndSession(var Message: TWMQueryEndSession);
435begin
436Showmessage('computer is about to shut down');
437end;
438
439◇[DELPHI]获取网上邻居
440procedure getnethood();//NT做服务器,WIN98上调试通过。
441var
442a,i:integer;
443errcode:integer;
444netres:array[0..1023] of netresource;
445enumhandle:thandle;
446enumentries:dword;
447buffersize:dword;
448s:string;
449mylistitems:tlistitems;
450mylistitem:tlistitem;
451alldomain:tstrings;
452begin //listcomputer is a listview to list all computers;controlcenter is a form.
453alldomain:=tstringlist.Create ;
454with netres[0] do begin
455dwscope :=RESOURCE_GLOBALNET;
456dwtype :=RESOURCETYPE_ANY;
457dwdisplaytype :=RESOURCEDISPLAYTYPE_DOMAIN;
458dwusage :=RESOURCEUSAGE_CONTAINER;
459lplocalname :=nil;
460lpremotename :=nil;
461lpcomment :=nil;
462lpprovider :=nil;
463end; // 获取所有的域
464errcode:=wnetopenenum(RESOURCE_GLOBALNET,RESOURCETYPE_ANY,RESOURCEUSAGE_CONTAINER,@netres[0],enumhandle);
465if errcode=NO_ERROR then begin
466enumentries:=1024;
467buffersize:=sizeof(netres);
468errcode:=wnetenumresource(enumhandle,enumentries,@netres[0],buffersize);
469end;
470a:=0;
471mylistitems :=controlcenter.lstcomputer.Items ;
472mylistitems.Clear ;
473while (string(netres[a].lpprovider)<>'') and (errcode=NO_ERROR) do
474begin
475alldomain.Add (netres[a].lpremotename);
476a:=a+1;
477end;
478wnetcloseenum(enumhandle);
479// 获取所有的计算机
480mylistitems :=controlcenter.lstcomputer.Items ;
481mylistitems.Clear ;
482for i:=0 to alldomain.Count-1 do
483begin
484with netres[0] do begin
485dwscope :=RESOURCE_GLOBALNET;
486dwtype :=RESOURCETYPE_ANY;
487dwdisplaytype :=RESOURCEDISPLAYTYPE_SERVER;
488dwusage :=RESOURCEUSAGE_CONTAINER;
489lplocalname :=nil;
490lpremotename :=pchar(alldomain[i]);
491lpcomment :=nil;
492lpprovider :=nil;
493end;
494ErrCode:=WNetOpenEnum(RESOURCE_GLOBALNET,RESOURCETYPE_ANY,RESOURCEUSAGE_CONTAINER,@netres[0],EnumHandle);
495if errcode=NO_ERROR then
496begin
497EnumEntries:=1024;
498BufferSize:=SizeOf(NetRes);
499ErrCode:=WNetEnumResource(EnumHandle,EnumEntries,@NetRes[0],BufferSize);
500end;
501a:=0;
502while (string(netres[a].lpprovider)<>'') and (errcode=NO_ERROR) do
503begin
504mylistitem :=mylistitems.Add ;
505mylistitem.ImageIndex :=0;
506mylistitem.Caption :=uppercase(stringreplace(string(NetRes[a].lpremotename),'\\\','',[rfReplaceAll]));
507a:=a+1;
508end;
509wnetcloseenum(enumhandle);
510end;
511end;
512
513◇[DELPHI]获取某一计算机上的共享目录
514procedure getsharefolder(const computername:string);
515var
516errcode,a:integer;
517netres:array[0..1023] of netresource;
518enumhandle:thandle;
519enumentries,buffersize:dword;
520s:string;
521mylistitems:tlistitems;
522mylistitem:tlistitem;
523mystrings:tstringlist;
524begin
525with netres[0] do begin
526dwscope :=RESOURCE_GLOBALNET;
527dwtype :=RESOURCETYPE_DISK;
528dwdisplaytype :=RESOURCEDISPLAYTYPE_SHARE;
529dwusage :=RESOURCEUSAGE_CONTAINER;
530lplocalname :=nil;
531lpremotename :=pchar(computername);
532lpcomment :=nil;
533lpprovider :=nil;
534end; // 获取根结点
535errcode:=wnetopenenum(RESOURCE_GLOBALNET,RESOURCETYPE_DISK,RESOURCEUSAGE_CONTAINER,@netres[0],enumhandle);
536if errcode=NO_ERROR then
537begin
538EnumEntries:=1024;
539BufferSize:=SizeOf(NetRes);
540ErrCode:=WNetEnumResource(EnumHandle,EnumEntries,@NetRes[0],BufferSize);
541end;
542wnetcloseenum(enumhandle);
543a:=0;
544mylistitems:=controlcenter.lstfile.Items ;
545mylistitems.Clear ;
546while (string(netres[a].lpprovider)<>'') and (errcode=NO_ERROR) do
547begin
548with mylistitems do
549begin
550mylistitem:=add;
551mylistitem.ImageIndex :=4;
552mylistitem.Caption :=extractfilename(netres[a].lpremotename);
553end;
554a:=a+1;
555end;
556end;
557
558◇[DELPHI]得到硬盘序列号
559var SerialNum : pdword; a, b : dword; Buffer : array [0..255] of char;
560begin
561if GetVolumeInformation('c:\', Buffer, SizeOf(Buffer), SerialNum, a, b, nil, 0) then Label1.Caption := IntToStr(SerialNum^);
562end;
563
564◇[DELPHI]MEMO的自动翻页
565Procedure ScrollMemo(Memo : TMemo; Direction : char);
566begin
567case direction of
568'd': begin
569SendMessage(Memo.Handle, { HWND of the Memo Control }
570WM_VSCROLL, { Windows Message }
571SB_PAGEDOWN, { Scroll Command }
5720) { Not Used }
573end;
574
575'u' : begin
576SendMessage(Memo.Handle, { HWND of the Memo Control }
577WM_VSCROLL, { Windows Message }
578SB_PAGEUP, { Scroll Command }
5790); { Not Used }
580end;
581end;
582end;
583
584procedure TForm1.Button1Click(Sender: TObject);
585begin
586ScrollMemo(Memo1,'d'); //上翻页
587end;
588procedure TForm1.Button1Click(Sender: TObject);
589begin
590ScrollMemo(Memo1,'u'); //下翻页
591end;
592
593◇[DELPHI]DBGrid中回车到下个位置(Tab键)
594procedure TForm1.DBGrid1KeyPress(Sender: TObject; var Key: Char);
595begin
596if Key = #13 then
597if DBGrid1.Columns.Grid.SelectedIndex < DBGrid1.Columns.Count - 1 then
598DBGrid1.Columns[DBGrid1.Columns.grid.SelectedIndex + 1].Field.FocusControl
599else
600begin
601Table1.next;
602DBGrid1.Columns[0].field.FocusControl;
603end;
604end;
605
606◇[DELPHI]如何安装控件
607安装方法:
6081.对于单个控件,Component-->install component..-->PAS或DCU文件-->install
6092.对于带*.dpk文件的控件包,File-->open(下拉列表框中选*.dpk)-->install即可.
6103.对于带*.dpl文件的控件包,Install Packages-->Add-->dpl文件名即可。
6114.如果以上Install按钮为失效的话,试试Compile按钮。
6125.是run time lib则在option下的packages下的runtimepackes加之.
613如果编译时提示文件找不到的话,一般是控件的安装目录不在delphi的Lib目录中,有两种方法可以解决:
6141.把安装的原文件拷入到delphi的Lib目录下。
6152.或者Tools-->Environment Options中把控件原代码路径加入到Delphi的Lib目录中即可。
616
617◇[DELPHI]目录完全删除(deltree)
618procedure TForm1.DeleteDirectory(strDir:String);
619var
620sr: TSearchRec;
621FileAttrs: Integer;
622strfilename:string;
623strPth:string;
624begin
625strpth:=Getcurrentdir();
626FileAttrs := faAnyFile;
627if FindFirst(strpth+'\'+strdir+'\\*.*', FileAttrs, sr) = 0 then
628begin
629if (sr.Attr and FileAttrs) = sr.Attr then
630begin
631strfilename:=sr.Name;
632if fileexists(strpth+'\'+strdir+'\'+strfilename) then
633deletefile(strpth+'\'+strdir+'\'+strfilename);
634end;
635while FindNext(sr) = 0 do
636begin
637if (sr.Attr and FileAttrs) = sr.Attr then
638begin
639strfilename:=sr.name;
640if fileexists(strpth+'\'+strdir+'\'+strfilename) then
641deletefile(strpth+'\'+strdir+'\'+strfilename);
642end;
643end;
644FindClose(sr);
645removedir(strpth+'\'+strdir);
646end;
647end;
648
649◇[DELPHI]取得TMemo 控件当前光标的行和列信息到Tpoint中
6501.function ReadCursorPos(SourceMemo: TMemo): TPoint;
651var Point: TPoint;
652begin
653point.y := SendMessage(SourceMemo.Handle,EM_LINEFROMCHAR,SourceMemo.SelStart,0);
654point.x := SourceMemo.SelStart-SendMessage(SourceMemo.Handle,EM_LINEINDEX,point.y,0);
655Result := Point;
656end;
6572.LineLength:=SendMessage(memol.handle,EM—LINELENGTH,Cpos,0);//行长
658
659◇[DELPHI]读硬盘序列号
660function GetDiskSerial(DiskChar: Char): string;
661var
662SerialNum : pdword;
663a, b : dword;
664Buffer : array [0..255] of char;
665begin
666result := "";
667if GetVolumeInformation(PChar(diskchar+":\"), Buffer, SizeOf(Buffer), SerialNum,
668a, b, nil, 0) then
669Result := IntToStr(SerialNum^);
670end;
671
672◇[INTERNET]CSS常用综合技巧
6731。P:first-letter { font-size: 300%; float: left }//首字会比普通字体加大三倍。
6742。<link href="basics.css" rel="StyleSheet" title="Contemporary"/>//连接一个外部样式表
6753。嵌入一个样式表
676<style media="screen" type="text/css">
677<!--
678@import url(http://www.htmlhelp.com/style.css);//外部导入一个样式表
679@import url(/stylesheets/punk.css);//同上
680BODY { background: url(foo.gif) red; color: black }
681.punk { color: lime; background: #ff80c0 }//引用见5。
682#wdg97 { font-size: larger }//引用见6。
683\-->
684</style>
6854。<p style="color: red; font-family: 'New Century Schoolbook', serif"> //内联样式
686<span style="font-family: Arial">Arial</span>//SPAN接受STYLE、CLASS和ID属性
687<div class="note"><p>DIV可以包含段落、标题、表格甚至其它部分</p></div>
6885。<h1 class="punk">CLASS属性</h1>//定义见3。
6896。<p id="wdg97">ID属性</p>//定义见3。
6907。属性列表
691字体风格:font-style: [normal | italic | oblique];
692字体大小:font-size: [xx-small | x-small | small | medium | large | x-large | xx-large | larger | smaller | <长度> | <百分比>]
693文本修饰:text-decoration:[ underline || overline || line-through || blink ]
694文本转换:text-transform:[none | capitalize | uppercase | lowercase]
695背景颜色:background-color:[<颜色> | transparent]
696背景图象:background-image:[<urls> | none]
697行高:line-height: [normal | <数字> | <长度> | <百分比>]
698边框样式:border-style: [ none | dotted | dashed | solid | double | groove | ridge | inset | outset ]
699漂浮:float: [left | right | none]
7008。长度单位
701相对单位:
702em (em,元素的字体的高度)
703ex (x-height,字母 "x" 的高度)
704px (像素,相对于屏幕的分辨率)
705绝对长度:
706in (英寸,1英寸=2.54厘米)
707cm (厘米,1厘米=10毫米)
708mm (米)
709pt (点,1点=1/72英寸)
710pc (帕,1帕=12点)
711
712◇[DELPHI]VCL制作简要步骤
7131.创建部件属性方法事件
714(建立库单元,继承为新的类型,添加属性、方法、事件,注册部件,建立包文件)
7152.消息处理
7163.异常处理
7174.部件可视
718
719◇[DELPHI]动态连接库的装载
720静态装载:procedure name;external 'lib.dll';
721动态装载:var handle:Thandle;
722handle:=loadlibrary('lib.dll');
723if handle<>0 then
724begin
725{dosomething}
726freelibrary(handle);
727end;
728
729◇[DELPHI]指针变量和地址
730var x,y:integer;p:^integer;//指向INTEGER变量的指针
731x:=10;//变量赋值
732p:=@x;//变量x的地址
733y:=p^;//为Y赋值指针P
734@@procedure//返回过程变量的内存地址
735
736◇[DELPHI]判断字符是汉字的一个字符
737ByteType('你好haha吗',1) = mbLeadByte//是第一个字符
738ByteType('你好haha吗',2) = mbTrailByte//是第二个字符
739ByteType('你好haha吗',5) = mbSingleByte//不是中文字符
740
741◇[DELPHI]memo的定位操作
742memo1.lines.delete(0)//删除第1行
743memo1.selstart:=10//定位10字节处
744
745◇[DELPHI]获得双字节字符内码
746function getit(s: string): integer;
747begin
748Result := byte(s[1]) * $100 + byte(s[2]);
749end;
750使用:getit('计')//$bcc6 即十进制 48326
751
752◇[DELPHI]调用ADD数据存储过程
753存储过程如下:
754create procedure addrecord(
755record1 varchar(10)
756record2 varchar(20)
757)
758as
759begin
760insert into tablename (field1,field2) values(:record1,:record2)
761end
762执行存储过程:
763EXECUTE procedure addrecord("urrecord1","urrecord2")
764
765◇[DELPHI]将文件存到blob字段中
766function blobcontenttostring(const filename: string):string;
767begin
768with tfilestream.create(filename,fmopenread) do
769try
770setlength(Result,size);
771read(Pointer(Result)^,size);
772finally
773free;
774end;
775end;
776//保存字段
777begin
778if (opendialog1.execute) then
779begin
780sFileName:=OpenDialog1.FileName;
781adotable1.edit;
782adotable1.fieldbyname('visio').asstring:=Blobcontenttostring(FileName);
783adotable1.post;
784end;
785
786◇[DELPHI]把文件全部复制到剪贴板
787uses shlobj,activex,clipbrd;
788procedure Tform1.copytoclipbrd(var FileName:string);
789var
790FE:TFormatEtc;
791Medium: TStgMedium;
792dropfiles:PDropFiles;
793pFile:PChar;
794begin
795FE.cfFormat := CF_HDROP;
796FE.dwAspect := DVASPECT_CONTENT;
797FE.tymed := TYMED_HGLOBAL;
798Medium.hGlobal := GlobalAlloc(GMEM_SHARE or GMEM_ZEROINIT, SizeOf(TDropFiles)+length(FileName)+1);
799if Medium.hGlobal<>0 then begin
800Medium.tymed := TYMED_HGLOBAL;
801dropfiles := GlobalLock(Medium.hGlobal);
802try
803dropfiles^.pfiles := SizeOf(TDropFiles);
804dropfiles^.fwide := False;
805longint(pFile) := longint(dropfiles)+SizeOf(TDropFiles);
806StrPCopy(pFile,FileName);
807Inc(pFile, Length(FileName)+1);
808pFile^ := #0;
809finally
810GlobalUnlock(Medium.hGlobal);
811end;
812Clipboard.SetAsHandle(CF_HDROP,Medium.hGlobal);
813end;
814end;
815
816◇[DELPHI]列举当前系统运行进程
817uses TLHelp32;
818procedure TForm1.Button1Click(Sender: TObject);
819var lppe: TProcessEntry32;
820found : boolean;
821Hand : THandle;
822begin
823Hand := CreateToolhelp32Snapshot(TH32CS_SNAPALL,0);
824found := Process32First(Hand,lppe);
825while found do
826begin
827ListBox1.Items.Add(StrPas(lppe.szExeFile));
828found := Process32Next(Hand,lppe);
829end;
830end;
831
832◇[DELPHI]根据BDETable1建立新表Table2
833Table2:=TTable.Create(nil);
834try
835Table2.DatabaseName:=Table1.DatabaseName;
836Table2.FieldDefs.Assign(Table1.FieldDefs);
837Table2.IndexDefs.Assign(Table1.IndexDefs);
838Table2.TableName:='new_table';
839Table2.CreateTable();
840finally
841Table2.Free();
842end;
843
844◇[DELPHI]最菜理解DLL建立和引用
845//先看DLL source(FILE-->NEW-->DLL)
846library project1;
847uses
848SysUtils, Classes;
849function addit(f:integer;s:integer):integer;export;
850begin
851makeasum:=f+s;
852end;
853exports
854addit;
855end.
856//调用(IN ur PROJECT)
857implementation
858function addit(f:integer;s:integer):integer;far;external 'project1';//申明
859{调用就是addit(2,4);结果显示6}
860
861◇[DELPHI]动态读取程序自身大小
862function GesSelfSize: integer;
863var
864f: file of byte;
865begin
866filemode := 0;
867assignfile(f, application.exename);
868reset(f);
869Result := filesize(f);//单位是字节
870closefile(f);
871end;
872
873◇[DELPHI]读取BIOS信息
874with Memo1.Lines do
875begin
876Add('MainBoardBiosName:'+^I+string(Pchar(Ptr($FE061))));
877Add('MainBoardBiosCopyRight:'+^I+string(Pchar(Ptr($FE091))));
878Add('MainBoardBiosDate:'+^I+string(Pchar(Ptr($FFFF5))));
879Add('MainBoardBiosSerialNo:'+^I+string(Pchar(Ptr($FEC71))));
880end;
881
882◇[DELPHI]动态建立MSSQL别名
883procedure TForm1.Button1Click(Sender: TObject);
884var MyList: TStringList;
885begin
886MyList := TStringList.Create;
887try
888with MyList do
889begin
890Add('SERVER NAME=210.242.86.2');
891Add('DATABASE NAME=db');
892Add('USER NAME=sa');
893end;
894Session1.AddAlias('TESTSQL', 'MSSQL', MyList); //</urls></p></e|e>