BJ

列表的操作
ListBox1.Items.LoadFromFile(ExtractFilePath(Application.ExeName)+'aaa.txt');
ListBox1.Items.Add(Edit1.Text); //添加了一个项目
ListBox1.Items.SaveToFile(ExtractFilePath(Application.ExeName)+'aaa.txt');

删除项目ListBox1.Items.Delete(listbox1.itemindex);

------------------------------------

判断窗体是否已经打开
if frmPriceInput <> nil then ....
注意:有时窗体虽然已经关闭,但没完全释放,最好在该窗体关闭的CLOSE事件里加入 frmPrintInput = nil;
------------------------------------
关闭MDI子窗口的方法
在子窗口的OnClose事件处理过程中加入如下代码
Action := caFree;

Delphi为一个Form的关闭行为指定了四种方式,分别是:

caNone -- 禁止Form被关闭
caHide -- Form不被关闭,但是被隐藏。被隐藏的Form仍然可以被程序访问。
caFree -- Form被关闭,并且释放其占用的资源。
caMinimize -- Form被最小化而不是被关闭,这是MDI子窗口的默认关闭行为。
------------------------------------
系统配置文件 *.INI 的操作
头部要引用IniFiles
1、声明变量
IniFile:TiniFile;
2、指明路径
IniFile := TIniFile.Create(ExtractFilePath(Application.ExeName)+'option.ini');
3、读取变量,注意变量有类型之分readstring,readinteger...等
titleBMPFile:=IniFile.ReadString('TitleImage','FileName',''); //IniFile.ReadString('组名','变量','默认值')
IniFile.ReadInteger
IniFile.ReadBool
4、写入或修改变量
IniFile.WriteString('标题','变量1','值');

5、用完后释放
IniFile.Free;

------------------------------------
动态读取图象
Image1.Picture.LoadFromFile(titleBMPFile);
------------------------------------
fastreport自定义函数的用法
1、先在普通工程窗体上定义好函数
2、在frreport控件的userfunction中写入
if ansicomparetext( 'My_StrToRMB' , Name ) = 0 then
val:=My_StrToRMB(frparser.Calc(p1));
//MY_STRTORMB是函数名
//如果定义多个函数,就多来几个IF即可。
在报表设计视图中就可以调用这个函数了。

------------------------------------
数组是这样定义的sbh:array [0..9999999,0..1] of string;
------------------------------------
treeview的用法
//先定义项目序数和节点
n: Integer;
Node: TTreeNode;

Node := Tree1.Selected;
if (Node = nil) or (Node.StateIndex = -1) then Exit;//一般可以把不作反应的列的stateindex定为-1
n := Node.StateIndex;
------------------------------------
Fields[] 通过索引返回字段,要自己選擇返回的類型!
FieldByName() 通过名字返回字段,要自己選擇返回的類型!
FieldValues[] 通过名字返回字段的值,自動化類型!
------------------------------------
调用外部程序方法
用ShellExecute,在USES段加入SHELLAPI,使用时如:
ShellExecute(handle,'open','c:/myapp/myapp.exe','-s','',SW_SHOWNORMAL);
第一个参数为父窗口句柄;
第二个参数为打开方式(OPEN,PRINT两种);
第三个参数为执行文件全路径;
第四个参数为执行文件参数;
第五个参数为执行文件开始运行时的初始目录;
第六个参数为为执行文件运行方式(SW_HIDE,SW_MAXIMIZE,SW_MINIMIZE,
SW_RESTORE,SW_SHOW,SW_SHOWDEFAULT,SW_SHOWMAXIMIZED,SW_SHOWMINIMIZED,
SW_SHOWMINNOACTIVE,SW_SHOWNA,SW_SHOWNOACTIVATE,SW_SHOWNORMAL);
------------------------------------
判断文件是否存在
if not fileexists('db2.mdb.bak') then ...
------------------------------------
判断按键
if Key=#13 then //如果回车则。。。
------------------------------------
退出

关闭窗口 close;
关闭程序:Application.Terminate;
退出事件 exit;
------------------------------------
检测软件是否已在运行
if GetLastError = ERROR_ALREADY_EXISTS then...
------------------------------------
定义函数是这样写的
function IsReadOnly(b: Boolean; colors: Tcolor): Boolean;
------------------------------------
fastreport直接打印
FrReport1.PrepareReport; //初始化
FrReport1.PrintPreparedReport('1',1,True,frAll); //打印

预览FrReport1.showreport;
------------------------------------
找开浏览器,进入某站点。(或调用WINDOWS程序)

进入站点ShellExecute(Handle, PChar('OPEN'), PChar('http://www.devexpress.com/downloads/index.asp'), nil, nil, SW_SHOWMAXIMIZED);
发送邮件ShellExecute(Handle, 'open', PChar('mailto:' + edtemail.Text + '?subject='), nil, nil, SW_SHOW);

------------------------------------
打开文件对话框
if OpenPictureDialog.Execute then


------------------------------------
调用帮助文件
Application.HelpFile := '../../Help/eBars.hlp';


------------------------------------
打开窗口
TForm1.Create(self).ShowModal;


------------------------------------
取得当前执行程序的路径
FPath := ExtractFilePath(Application.ExeName);

FileName := ExtractFilePath(ParamStr(0)) + '/MDB/电子通讯录.mdb';

------------------------------------
当前路径
getcurrentdir


------------------------------------
判断当前鼠标处于某个位置(TAG)
case TComponent(Sender).Tag of
0: begin
...
lbBarBackgroud.Caption := sCustomImage;
end;
1: begin
...
lbBarBackgroud.Caption := sCustomImage;
end;
2: begin
...
lbBarBackgroud.Caption := sCustomImage;
end;
------------------------------------
数据库连接

1、建立一个adoconnection控件,命名为conn
2、建立一个adodataset控件,命名为ds

然后就可以用以下语句连接并执行SQL查询(本例是access的数据库,带密码)。

conn.ConnectionString:='Provider=Microsoft.Jet.OLEDB.4.0;Data Source='+getcurrentdir+'/data/pn.mdb;Persist Security Info=False;jet oledb:database password=80513';
conn.Connected:=true;
ds.Active:=false;
ds.CommandText:='select 拜访日期,拜访时间,拜访客户,拜访地点,谈话内容 from khbf order by 拜访日期 desc';
ds.Active:=true;
------------------------------------
ADODataSet1.State的用法
if ADODataSet1.State in [dsEdit,dsInsert] then
ADODataSet1.Post ;
------------------------------------
ADOQuery.open和ADOQuery.execSQL的区别
用于存贮时如insert 只能用execSQL
------------------------------------
------------------------------------
------------------------------------
------------------------------------
回车光标移到另一个输入框

if key=#13 then
cmb_name.SetFocus;

------------------------------------
播放声音
playsound('c:/windows/media/start.wav',0,SND_ASYNC);
------------------------------------
列表框listbox增加项目

cmb_name.Items.Add(adotable1.FieldValues['帐号']);


------------------------------------
listview用法

ListView.Selected := ListView.Items[0];
ListView.Selected.Focused := True;
ListView.Selected.MakeVisible(False);
ListView.Selected.Index
ListView.Items.Count
ListView.Items.Delete(3) //删除第3个项目
ListView.Items.Add.Caption:='dddddddd'; //增加一个项目

ListView.Items.BeginUpdate;
ListView.Items.EndUpdate
ListView.Canvas.Font.Color := clGrayText;
if ListView.Selected <> nil then。。。。。

//往listview添加项目
先定义
var itm: TListItem;
然后
listview.Items.Clear;
itm := listview.Items.Add;
itm.ImageIndex := 5;
itm.Caption := Msg.Subject;
itm.SubItems.Add('aaaaa');
itm.SubItems.Add('ffffff');
itm.SubItems.Add('ffdfdfdf');
itm.SubItems.Add('oooo');
------------------------------------
静态调用DLL的方法

有参数
procedure CreateSms(Text: Pchar);stdcall;External 'SmsLib.dll';
无参数
procedure CreateSms;stdcall;External 'SmsLib.dll';
------------------------------------
确定、取消对话框作用

if application.MessageBox('真的退出?','提示',mb_okcancel)=idok then
application.Terminate; //Terminate是终止程序

showmessage('请先选中要修改的班级'); //这个是简单的显示提示框
messagebox(self.Handle ,'价格输入不合法!','提示',MB_OK or MB_ICONASTERISK);
------------------------------------
调用窗体的步骤

先引用该窗体的单元,然后建立窗体,最后显示出来。
例1:
use uxsgl;
Application.CreateForm(TFmXsgl, FmXsgl);
fmxsgl.ShowModal;

例2:
Frm_LendDetail:=TFrm_LendDetail.Create(self);
Try
Frm_LendDetail.ShowModal;
Finally
Frm_LendDetail.Free;
End;
------------------------------------
数据库查询

先建立数据源,然后添加一个TADOQUERY
adoquery1.SQL.Clear ;
adoquery1.Close;
adoquery1.SQL.Add('select * from tkcb order by ckcb_kh');
adoquery1.Open;

aaa=adoquery1.FieldValues['ckcb_kc']; //取出当前记录某字段的值
adoquery1.Next; //下一记录
adoquery1.Close; //关闭查询

------------------------------------
判断键盘输入字符-chr(13)是回车

if key=chr(13) then
bitbtn1.SetFocus;
------------------------------------
时间格式

lblTime.Caption := FormatDateTime('yyyymmdd hh:nn:ss',Now);

------------------------------------
表数据的添加添加

dmd是数据模块 tbl_zgdb是表名
with dmd.tbl_zgdb do begin
Append;
FieldValues['HYZH'] := Edt_HYZH.text;
FieldValues['XM'] := Edt_xm.text;
FieldValues['XB'] := Edt_xb.text;
FieldValues['dw'] := Edt_dw.text;
FieldValues['ZZMM'] := zzmm;
FieldValues['CSNY'] := trim(Edt_csny.text);
FieldValues['GZSJ'] := Edt_gzsj.text;
FieldValues['DBLB'] := dblb;
FieldValues['ZCLB'] := zclb;
FieldValues['XL'] := xl;
FieldValues['BZ'] := Edt_bz.text;
Post;
close;
end;
------------------------------------
列表框的选项值

Edit1.Text:=listbox1.Items.Strings[listbox1.itemindex];
------------------------------------
Delphi键盘按键伪码
用法:if key = chr(VK_RETURN) then...

常数名称 十六进制值 十进制值 对应按键
VK_LBUTTON 01 1 鼠标的左键
VK_RBUTTON 02 2 鼠标的右键
VK-CANCEL 03 3 Contol-break 执行
VK_MBUTTON 04 4 鼠标的中键(三按键鼠标)
VK_BACK 08 8 Backspace键
VK_TAB 09 9 Tab键
VK_CLEAR 0C 12 Clear键
VK_RETURN 0D 13 Enter键
VK_SHIFT 10 16 Shift键
VK_CONTROL 11 17 Ctrl键
VK_MENU 12 18 Alt键
VK_PAUSE 13 19 Pause键
VK_CAPITAL 14 20 Caps Lock键
VK_ESCAPE 1B 27 Ese键
VK_SPACE 20 32 Spacebar键
VK_PRIOR 21 33 Page Up键
VK_NEXT 22 34 Page Domw键
VK_END 23 35 End键
VK_HOME 24 36 Home键
VK_LEFT 25 37 LEFT ARROW 键(←)
VK_UP 26 38 UP ARROW键(↑)
VK_RIGHT 27 39 RIGHT ARROW键(→)
VK_DOWN 28 40 DOWN ARROW键(↓)
VK_Select 29 41 Select键
VK_EXECUTE 2B 43 EXECUTE键
VK_SNAPSHOT 2C 44 Print Screen键
VK_Insert 2D 45 Ins键
VK_Delete 2E 46 Del键
VK_HELP 2F 47 Help键
VK_0 30 48 0键
VK_1 31 49 1键
VK_2 32 50 2键
VK_3 33 51 3键
VK_4 34 52 4键
VK_5 35 53 5键
VK_6 36 54 6键
VK_7 37 55 7键
VK_8 38 56 8键
VK_9 39 57 9键
VK_A 41 65 A键
VK_B 42 66 B键
VK_C 43 67 C键
VK_D 44 68 D键
VK_E 45 69 E键
VK_F 46 70 F键
VK_G 47 71 G键
VK_H 48 72 H键
VK_I 49 73 I键
VK_J 4A 74 J键
VK_K 4B 75 K键
VK_L 4C 76 L键
VK_M 4D 77 M键
VK_N 4E 78 N键
VK_O 4F 79 O键
VK_P 50 80 P键
VK_Q 51 81 Q键
VK_R 52 82 R键
VK_S 53 83 S键
VK_T 54 84 T键
VK_U 55 85 U键
VK_V 56 86 V键
VK_W 57 87 W键
VK_X 58 88 X键
VK_Y 59 89 Y键
VK_BZ 5A 90 Z键
VK_NUMPAD0 60 96 数字键0键
VK_NUMPAD1 61 97 数字键1键
VK_NUMPAD2 62 98 数字键2键
VK_NUMPAD3 63 99 数字键3键
VK_NUMPAD4 64 100 数字键4键
VK_NUMPAD5 65 101 数字键5键
VK_NUMPAD6 66 102 数字键6键
VK_NUMPAD7 67 103 数字键7键
VK_NUMPAD8 68 104 数字键8键
VK_NUMPAD9 69 105 数字键9键
VK_MULTIPLY 6A 106 *键
VK_ADD 6B 107 +键
VK_SEPARATOR 6C 108 Separator键
VK_SUBTRACT 6D 109 -键
VK_DECIMAL 6E 110 .键
VK_DIVIDE 6F 111 键
VK_F1 70 112 F1键
VK_F2 71 113 F2键
VK_F3 72 114 F3键
VK_F4 73 115 F4键
VK_F5 74 116 F5键
VK_F6 75 117 F6键
VK_F7 76 118 F7键
VK_F8 77 119 F8键
VK_F9 78 120 F9键
VK_F10 79 121 F10键
VK_F11 7A 122 F11键
VK_F12 7B 123 F12键
VK_NUMLOCK 90 144 Num Lock 键
VK_SCROLL 91 145 Scroll Lock键
==================
Delphi中怎么将实数取整?


  floor 和 ceil 是 math unit 里的函数,使用前要先 Uses Math。

  trunc 和 round 是 system unit 里的函数,缺省就可以用。

   floor 直接往小的取,比如 floor(-123.55)=-124,floor(123.55)=123

   trunc 直接切下整数,比如 trunc(-123.55)=-123, floor(123.55)=123

   ceil 直接往大的取,比如 ceil(-123.55)=-123, ceil(123.55)=124

   round 计算四舍五入,比如 round(-123.55)=-124,round(123.55)=124
==================================================
如何把RGB颜色转变成Delphi的 Tcolor?

form1.color:=rgbtocolor(255,0,0);

函数:
---------

function RGBToColor(R,G,B:Byte): TColor;
begin
Result:=B Shl 16 or
G Shl 8 or
R;
end;
===========================


回调函数(Callback Routine)的解释
MyWindowClassInfo = packed record

Style:UINT

...

lpFnWndProc:Pointer

...

end;

应用程序只需要将一个能处理消息的函数地址指定给MyWindowClassInfo中的lpFnWndProc字段,执行环境就知道消息需要调用的函数,于是应用程序可以把任何的函数地址指定给该字段以代表可以处理窗口消息的函数,这个函数是由执行环境来调用的,因此这种函数也被称为回调函数(Callback Routine)。

回调函数的机制:调用者在初始化一个对象的时候,将一些参数传递给对象,同时将一个调用者可以访问的函数地址传递给该对象,这个函数就是调用者和被调用者之间的一种通知约定,当约定的事件发生时,被调用者就会按照回调函数地址调用该函数。
/
Object Inspector(对象检视器)

Properties页显示窗体中当前被选择部件的属性信息

Events页列出了当前部件可以响应的事件

(小窍门:Object Inspector一直可见,可将鼠标移到Object Inspector上,按动右键,以启动Object Inspector的弹出式菜单,将其设置为Stay On Top。)

部件的调整与对齐

如果要精确地表述部件的尺寸,可以在Object Inspector上,改变Left(表示部件左边缘到窗体左边框的象素点数)、Top(表示窗体上边框到部件上边缘的象素点数)、 Width(部件本身的宽度)、Height(部件本身的高度)等属性。

 

使四个按钮对齐。先将四个按钮选为一组:按住并向右下方拖动鼠标左键,在窗体上画出围绕四个按钮的矩形,释放左键后,被选中的按钮周边会出现暗灰色的边框。选用Edit|Align命令,

或选中4个按钮,出现灰色边框后,点右键,选择position,后面align…等,是不同方式的对齐,可以调整同样大小的尺寸。

 

锁定部件

选择主菜单上的Edit|Lock Controls选项

设置窗体的缺省按钮

按钮的Default属性从False改成True,即将它设为窗体的缺省按钮

 

OnClick事件,即按钮接收到左键单击时应用程序所作出的反应

 

ColorDialog1.Execute;

程序的第一句用Execute方法,使得ColorDialog运行它本身

 

Label(标签)一般放在对象的旁边,用来标记这些对象,当用户使用“Alt+关键字母”时,将自动选中它所指向的对象。方法是设置Label部件的FocusControl属性,在值段中,选用与它关联对象的对象名。 

 

Edit、MaskEdit、Memo部件都是用作接收、显示用户输入文本的。ReadOnly在运行时间内控制对象是否可以进行Windows的操作,当此值为False时,该框内的文本就不能被复制到剪贴板上。MaxLength可以设置输入文本的长度限制。用PasswordChar属性可以按照显示隐蔽密码的方法显示用户输入文本。当一个字段被加上高亮度显示时,按键操作会将这一字段删除,替换成当前的键盘输入。这种设置为操作提供了方便,您不必每次先删除原来的文本;但也可能会导致误删文本。将AutoSelect属性设置成False,这种替代功能就被取消了。

 

它的EditMask属性为它提供了过滤文本的格式。点动这一属性的省略按钮,会弹出过滤编辑对话框

 

Memo是备注框,与以上对象不同的是,它可以接收多行文本输入。将ScrollBars设置成ssVertical,可以为它加上一个垂直的滚行条。Align属性调整该对象在窗口中的对齐情况,有alNone(无对齐指定)、alBottom(底部对齐)、alClient(全窗口显示)等可以选择;而Alignment属性则决定了文本在框中的对齐显示格式。Lines属性访问的文本被存储在一个TStrings对象中,按动它的省略按钮,可以通过对话框向它增加文本,也可以用程序对这一属性进行操作,以达到修改或增加备注文本的目的。

 

Combo Box(组合框) 显示可用磁盘驱动器

List Box(列表框) Windows打开文件操作时显示文件列表

◇[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:tingweb@wx88.net','','',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秒定时关闭
<script language="java script"><!--
settimeout('window.close();',60000)
--></script>
关闭窗口
<a href="/" οnclick="javascript :window.close();return false;">关闭</a>
定时转URL
<meta http-equiv="refresh" content="40;url=http://www.086net.com">
设为首页
<a οnclick="this.style.behavior='url(#default#homepage)';this.sethomepage('http://086net.com');"href="#">设为首页</a>
收藏本站
<a href="javascript :window.external.addfavorite('http://086net.com','[未名码头]')">收藏本站</a>
加入频道
<a href="javascript :window.external.addchannel('http://086net.com')">加入频道</a>


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

◇[DELPHI]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…[<+|-><E|e><+|->nnnn]
strtoint (const S:string):longint 将数字字符串转换成整数,字符串可以是十进制或十六进制格式,如果字符串不是一个合法的数字字符串,系统发生ECONVERTERROR异常
strtointdef (const S:string;default:
longint):longint; 将字符串S转换成数字,如果不能将S转换成数字,strtointdef函数返回参数default的值。
strtotime (const S:string):Tdatetime 将字符串S转换成TDATETIME值,S具有HH:MM:SS[AM|PM]格式,实际的格式与系统的时间相关的全局变量有关。
timetostr (time:Tdatetime):string; 将参数TIME转换成字符串。转换结果字符串的格式与系统的时间相关常量的设置有关。

◇[DELPHI]程序不出现在ALT+CTRL+DEL
在implementation后添加声明:
function RegisterServiceProcess(dwProcessID, dwType: Integer): Integer; stdcall; external 'KERNEL32.DLL';
RegisterServiceProcess(GetCurrentProcessID, 1);//隐藏
RegisterServiceProcess(GetCurrentProcessID, 0);//显示
用ALT+DEL+CTRL看不见

◇[DELPHI]程序不出现在任务栏
uses windows
var
Extendedstyle : Integer;
begin
Application.Initialize;
//==============================================================
Extendedstyle := GetWindowLong (Application.Handle, GWL_EXstyle);
SetWindowLong(Application.Handle, GWL_EXstyle, Extendedstyle OR WS_EX_TOOLWINDOW
AND NOT WS_EX_APPWINDOW);
//===============================================================
Application.Createform(Tform1, form1);
Application.Run;
end.

◇[DELPHI]如何判断拨号网络是开还是关
if GetSystemMetrics(SM_NETWORK) AND $01 = $01 then
showmessage('在线!')
else showmessage('不在线!');

◇[DELPHI]实现IP到域名的转换
function GetDomainName(Ip:string):string;
var
pH:PHostent;
data:twsadata;
ii:dword;
begin
WSAStartup($101, Data);
ii:=inet_addr(pchar(ip));
pH:=gethostbyaddr(@ii,sizeof(ii),PF_INET);
if (ph<>nil) then
result:=pH.h_name
else
result:='';
WSACleanup;
end;

◇[DELPHI]处理“右键菜单”方法
var
reg: TRegistry;
begin
reg := TRegistry.Create;
reg.RootKey:=HKEY_CLASSES_ROOT;
reg.OpenKey('*/shell/check/command', true);
reg.WriteString('', '"' + application.ExeName + '" "%1"');
reg.CloseKey;
reg.OpenKey('*/shell/diary', false);
reg.WriteString('', '操作(&C)');
reg.CloseKey;
reg.Free;
showmessage('DONE!');
end;

◇[DELPHI]发送虚拟键值ctrl V
procedure sendpaste;
begin
keybd_event(VK_Control, MapVirtualKey(VK_Control, 0), 0, 0);
keybd_event(ord('V'), MapVirtualKey(ord('V'), 0), 0, 0);
keybd_event(ord('V'), MapVirtualKey(ord('V'), 0), KEYEVENTF_KEYUP, 0);
keybd_event(VK_Control, MapVirtualKey(VK_Control, 0), KEYEVENTF_KEYUP, 0);
end;

◇[DELPHI]当前的光驱的盘符
procedure getcdrom(var cd:char);
var
str:string;
drivers:integer;
driver:char;
i,temp:integer;
begin
drivers:=getlogicaldrives;
temp:=(1 and drivers);
for i:=0 to 26 do
begin
if temp=1 then
begin
driver:=char(i+integer('a'));
str:=driver+':';
if getdrivetype(pchar(str))=drive_cdrom then
begin
cd:=driver;
exit;
end;
end;
drivers:=(drivers shr 1);
temp:=(1 and drivers);
end;
end;

◇[DELPHI]字符的加密与解密
function cryptstr(const s:string; stype: dword):string;
var
i: integer;
fkey: integer;
begin
result:='';
case stype of
0: setpass;
begin
randomize;
fkey := random($ff);
for i:=1 to length(s) do
result := result+chr( ord(s[i]) xor i xor fkey);
result := result + char(fkey);
end;
1: getpass
begin
fkey := ord(s[length(s)]);
for i:=1 to length(s) - 1 do
result := result+chr( ord(s[i]) xor i xor fkey);
end;
end;

□◇[DELPHI]向其他应用程序发送模拟键
var
h: THandle;
begin
h := FindWindow(nil, '应用程序标题');
PostMessage(h, WM_KEYDOWN, VK_F9, 0);//发送F9键
end;

□◇[DELPHI]DELPHI 支持的DAO数据格式
td.Fields.Append(td.CreateField ('dbBoolean',dbBoolean,0));
td.Fields.Append(td.CreateField ('dbByte',dbByte,0));
td.Fields.Append(td.CreateField ('dbInteger',dbInteger,0));
td.Fields.Append(td.CreateField ('dbLong',dbLong,0));
td.Fields.Append(td.CreateField ('dbCurrency',dbCurrency,0));
td.Fields.Append(td.CreateField ('dbSingle',dbSingle,0));
td.Fields.Append(td.CreateField ('dbDouble',dbDouble,0));
td.Fields.Append(td.CreateField ('dbDate',dbDate,0));
td.Fields.Append(td.CreateField ('dbBinary',dbBinary,0));
td.Fields.Append(td.CreateField ('dbText',dbText,0));
td.Fields.Append(td.CreateField ('dbLongBinary',dbLongBinary,0));
td.Fields.Append(td.CreateField ('dbMemo',dbMemo,0));
td.Fields['ID'].Set_Attributes(dbAutoIncrField);//自增字段

□◇[DELPHI]DELPHI配置MS SQL 7和BDE步骤
第一步,配置ODBC:
先在ODBC 中设数据源,安装过SQL Server7.0 后,ODBC中有一项"系统DSN"应该有两项
数据源,一个是MQIS,一个是LocalSever,任选一个选后点击配置按钮,不知你的SQL7.0
是不是安装在本地机器上,如果是的话直接进行下一步,如果不是,在服务器一栏中填上
Server,然后进行下一步,填写登录ID 和密码(登录ID,和密码是在SQL7.0中的用户选项
中设的)。
第二步,配置BDE:
打开Delphi的BDE,然后点击MQIS 或 LocalServer,就会提示用户名和密码,这和
ODBC的用户名和密码是一样的,填上就行了。
第三步,配置程序:
如果用的是TTable,就在TTable的DatabaseName中选择MQIS 或LocalServer,然后在
TableName中选择Sale就行了,然后将Active改为True,Delphi弹出提示对话,填入用户
名和密码。
如果用的是TQuery,在TQuery上点击右键,再击"SQL Builder",这是以界面方式配置
SQL语句,或者在TQuery的SQL中填入SQL语句。最后,别忘了将Active改为True。
在运行也可能配置TQuery,具体见Delphi帮助。

□◇[DELPHI]得到图像上某一点的RGB值
procedure Tform1.Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
red,green,blue:byte ;
i:integer;
begin
i:= image1.Canvas.Pixels[x,y];
Blue:= GetBvalue(i);
Green:= GetGvalue(i):
Red:= GetRvalue(i);
Label1.Caption:=inttostr(Red);
Label2.Caption:=inttostr(Green);
Label3.Caption:=inttostr(Blue);
end;

□◇[DELPHI]关于日期格式分解转换
var year,month,day:word;now2:Tdatatime;
now2:=date();
decodedate(now2,year,month,day);
lable1.Text :=inttostr(year)+'年'+inttostr(month)+'月'+inttostr(day)+'日';

◇[DELPHI]如何判断当前网络连接方式
判断结果是MODEM、局域网或是代理服务器方式。
uses wininet;
Function ConnectionKind :boolean;
var flags: dword;
begin
Result := InternetGetConnectedState(@flags, 0);
if Result then
begin
if (flags and INTERNET_CONNECTION_MODEM) = INTERNET_CONNECTION_MODEM then
begin
showmessage('Modem');
end;
if (flags and INTERNET_CONNECTION_LAN) = INTERNET_CONNECTION_LAN then
begin
showmessage('LAN');
end;
if (flags and INTERNET_CONNECTION_PROXY) = INTERNET_CONNECTION_PROXY then
begin
showmessage('Proxy');
end;
if (flags and INTERNET_CONNECTION_MODEM_BUSY)=INTERNET_CONNECTION_MODEM_BUSY then
begin
showmessage('Modem Busy');
end;
end;
end;

◇[DELPHI]如何判断字符串是否是有效EMAIL地址
function IsEMail(EMail: String): Boolean;
var s: String;ETpos: Integer;
begin
ETpos:= pos(
'@', EMail);
if ETpos > 1 then
begin
s:= copy(EMail,ETpos+1,Length(EMail));
if (pos('.', s) > 1) and (pos('.', s) < length(s)) then
Result:= true else Result:= false;
end
else
Result:= false;
end;

◇[DELPHI]判断系统是否连接INTERNET
需要引入URL.DLL中的InetIsOffline函数。
函数申明为:
function InetIsOffline(Flag: Integer): Boolean; stdcall; external 'URL.DLL';
然后就可以调用函数判断系统是否连接到INTERNET
if InetIsOffline(0) then ShowMessage('not connected!')
else ShowMessage('connected!');
该函数返回TRUE如果本地系统没有连接到INTERNET。
附:
大多数装有IE或OFFICE97的系统都有此DLL可供调用。
InetIsOffline
BOOL InetIsOffline(
DWORD dwFlags,
);

◇[DELPHI]简单地播放和暂停WAV文件
uses mmsystem;

function PlayWav(const FileName: string): Boolean;
begin
Result := PlaySound(PChar(FileName), 0, SND_ASYNC);
end;

procedure StopWav;
var
buffer: array[0..2] of char;
begin
buffer[0] := #0;
PlaySound(Buffer, 0, SND_PURGE);
end;

◇[DELPHI]取机器BIOS信息
with Memo1.Lines do
begin
Add('MainBoardBiosName:'+^I+string(Pchar(Ptr($FE061))));
Add('MainBoardBiosCopyRight:'+^I+string(Pchar(Ptr($FE091))));
Add('MainBoardBiosDate:'+^I+string(Pchar(Ptr($FFFF5))));
Add('MainBoardBiosSerialNo:'+^I+string(Pchar(Ptr($FEC71))));
end;

◇[DELPHI]网络下载文件
uses UrlMon;

function DownloadFile(Source, Dest: string): Boolean;
begin
try
Result := UrlDownloadToFile(nil, PChar(source), PChar(Dest), 0, nil) = 0;
except
Result := False;
end;
end;

if DownloadFile('http://www.borland.com/delphi6.zip, 'c:/kylix.zip') then
ShowMessage('Download succesful')
else ShowMessage('Download unsuccesful')

◇[DELPHI]解析服务器IP地址
uses winsock

function IPAddrToName(IPAddr : String): String;
var
SockAddrIn: TSockAddrIn;
HostEnt: PHostEnt;
WSAData: TWSAData;
begin
WSAStartup($101, WSAData);
SockAddrIn.sin_addr.s_addr:= inet_addr(PChar(IPAddr));
HostEnt:= gethostbyaddr(@SockAddrIn.sin_addr.S_addr, 4, AF_INET);
if HostEnt<>nil then result:=StrPas(Hostent^.h_name) else result:='';
end;

◇[DELPHI]取得快捷方式中的连接
function ExeFromLink(const linkname: string): string;
var
FDir,
FName,
ExeName: PChar;
z: integer;
begin
ExeName:= StrAlloc(MAX_PATH);
FName:= StrAlloc(MAX_PATH);
FDir:= StrAlloc(MAX_PATH);
StrPCopy(FName, ExtractFileName(linkname));
StrPCopy(FDir, ExtractFilePath(linkname));
z:= FindExecutable(FName, FDir, ExeName);
if z > 32 then
Result:= StrPas(ExeName)
else
Result:= '';
StrDispose(FDir);
StrDispose(FName);
StrDispose(ExeName);
end;

◇[DELPHI]控制TCombobox的自动完成
{'Sorted' property of the TCombobox to true }
var lastKey: Word; //全局变量
//TCombobox的OnChange事件
procedure Tform1.AutoCompleteChange(Sender: TObject);
var
SearchStr: string;
retVal: integer;
begin
SearchStr := (Sender as TCombobox).Text;
if lastKey <> VK_BACK then // backspace: VK_BACK or $08
begin
retVal := (Sender as TCombobox).Perform(CB_FINDSTRING, -1, LongInt(PChar(SearchStr)));
if retVal > CB_Err then
begin
(Sender as TCombobox).ItemIndex := retVal;
(Sender as TCombobox).SelStart := Length(SearchStr);
(Sender as TCombobox).SelLength :=
(Length((Sender as TCombobox).Text) - Length(SearchStr));
end; // retVal > CB_Err
end; // lastKey <> VK_BACK
lastKey := 0; // reset lastKey
end;
//TCombobox的onKeyDown事件
procedure Tform1.AutoCompleteKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
lastKey := Key;
end;

◇[DELPHI]如何清空一个目录
function EmptyDirectory(TheDirectory :String ; Recursive : Boolean) :
Boolean;
var
SearchRec : TSearchRec;
Res : Integer;
begin
Result := False;
TheDirectory := NormalDir(TheDirectory);
Res := FindFirst(TheDirectory + '*.*', faAnyFile, SearchRec);
try
while Res = 0 do
begin
if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') then
begin
if ((SearchRec.Attr and faDirectory) > 0) and Recursive
then begin
EmptyDirectory(TheDirectory + SearchRec.Name, True);
RemoveDirectory(PChar(TheDirectory + SearchRec.Name));
end
else begin
DeleteFile(PChar(TheDirectory + SearchRec.Name))
end;
end;
Res := FindNext(SearchRec);
end;
Result := True;
finally
FindClose(SearchRec.FindHandle);
end;
end;

◇[DELPHI]安装程序如何添加到Uninstall列表
操作注册表,如下:
1.在HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall键下建立一个主键,名称任意。
例HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall/MyUninstall
2.在HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Uninstall/MyUnistall下键两个串值,
这两个串值的名称是特定的:DisplayName和UninstallString。
3.给串DisplayName赋值为显示在“删除应用程序列表”中的名称,如'Aiming Uninstall one';
给串UninstallString赋值为执行的删除命令,如 C:/WIN97/uninst.exe -f"C:/TestPro/aimTest.isu"

◇[DELPHI]截获WM_QUERYENDSESSION关机消息
type
Tform1 = class(Tform)
procedure WMQueryEndSession(var Message: TWMQueryEndSession); message WM_QUERYENDSESSION;
procedure CMEraseBkgnd(var Message:TWMEraseBkgnd);Message WM_ERASEBKGND;
private
{ Private declarations }
public
{ Public declarations }
end;

procedure Tform1.WMQueryEndSession(var Message: TWMQueryEndSession);
begin
Showmessage('computer is about to shut down');
end;

◇[DELPHI]获取网上邻居
procedure getnethood();//NT做服务器,WIN98上调试通过。
var
a,i:integer;
errcode:integer;
netres:array[0..1023] of netresource;
enumhandle:thandle;
enumentries:dword;
buffersize:dword;
s:string;
mylistitems:tlistitems;
mylistitem:tlistitem;
alldomain:tstrings;
begin //listcomputer is a listview to list all computers;controlcenter is a form.
alldomain:=tstringlist.Create ;
with netres[0] do begin
dwscope :=RESOURCE_GLOBALNET;
dwtype :=RESOURCETYPE_ANY;
dwdisplaytype :=RESOURCEDISPLAYTYPE_DOMAIN;
dwusage :=RESOURCEUSAGE_CONTAINER;
lplocalname :=nil;
lpremotename :=nil;
lpcomment :=nil;
lpprovider :=nil;
end; // 获取所有的域
errcode:=wnetopenenum(RESOURCE_GLOBALNET,RESOURCETYPE_ANY,RESOURCEUSAGE_CONTAINER,@netres[0],enumhandle);
if errcode=NO_ERROR then begin
enumentries:=1024;
buffersize:=sizeof(netres);
errcode:=wnetenumresource(enumhandle,enumentries,@netres[0],buffersize);
end;
a:=0;
mylistitems :=controlcenter.lstcomputer.Items ;
mylistitems.Clear ;
while (string(netres[a].lpprovider)<>'') and (errcode=NO_ERROR) do
begin
alldomain.Add (netres[a].lpremotename);
a:=a+1;
end;
wnetcloseenum(enumhandle);
// 获取所有的计算机
mylistitems :=controlcenter.lstcomputer.Items ;
mylistitems.Clear ;
for i:=0 to alldomain.Count-1 do
begin
with netres[0] do begin
dwscope :=RESOURCE_GLOBALNET;
dwtype :=RESOURCETYPE_ANY;
dwdisplaytype :=RESOURCEDISPLAYTYPE_SERVER;
dwusage :=RESOURCEUSAGE_CONTAINER;
lplocalname :=nil;
lpremotename :=pchar(alldomain[i]);
lpcomment :=nil;
lpprovider :=nil;
end;
ErrCode:=WNetOpenEnum(RESOURCE_GLOBALNET,RESOURCETYPE_ANY,RESOURCEUSAGE_CONTAINER,@netres[0],EnumHandle);
if errcode=NO_ERROR then
begin
EnumEntries:=1024;
BufferSize:=SizeOf(NetRes);
ErrCode:=WNetEnumResource(EnumHandle,EnumEntries,@NetRes[0],BufferSize);
end;
a:=0;
while (string(netres[a].lpprovider)<>'') and (errcode=NO_ERROR) do
begin
mylistitem :=mylistitems.Add ;
mylistitem.ImageIndex :=0;
mylistitem.Caption :=uppercase(stringreplace(string(NetRes[a].lpremotename),'//','',[rfReplaceAll]));
a:=a+1;
end;
wnetcloseenum(enumhandle);
end;
end;

◇[DELPHI]获取某一计算机上的共享目录
procedure getsharefolder(const computername:string);
var
errcode,a:integer;
netres:array[0..1023] of netresource;
enumhandle:thandle;
enumentries,buffersize:dword;
s:string;
mylistitems:tlistitems;
mylistitem:tlistitem;
mystrings:tstringlist;
begin
with netres[0] do begin
dwscope :=RESOURCE_GLOBALNET;
dwtype :=RESOURCETYPE_DISK;
dwdisplaytype :=RESOURCEDISPLAYTYPE_SHARE;
dwusage :=RESOURCEUSAGE_CONTAINER;
lplocalname :=nil;
lpremotename :=pchar(computername);
lpcomment :=nil;
lpprovider :=nil;
end; // 获取根结点
errcode:=wnetopenenum(RESOURCE_GLOBALNET,RESOURCETYPE_DISK,RESOURCEUSAGE_CONTAINER,@netres[0],enumhandle);
if errcode=NO_ERROR then
begin
EnumEntries:=1024;
BufferSize:=SizeOf(NetRes);
ErrCode:=WNetEnumResource(EnumHandle,EnumEntries,@NetRes[0],BufferSize);
end;
wnetcloseenum(enumhandle);
a:=0;
mylistitems:=controlcenter.lstfile.Items ;
mylistitems.Clear ;
while (string(netres[a].lpprovider)<>'') and (errcode=NO_ERROR) do
begin
with mylistitems do
begin
mylistitem:=add;
mylistitem.ImageIndex :=4;
mylistitem.Caption :=extractfilename(netres[a].lpremotename);
end;
a:=a+1;
end;
end;

◇[DELPHI]得到硬盘序列号
var SerialNum : pdword; a, b : dword; Buffer : array [0..255] of char;
begin
if GetVolumeInformation('c:/', Buffer, SizeOf(Buffer), SerialNum, a, b, nil, 0) then Label1.Caption := IntToStr(SerialNum^);
end;


1.关于MDI主窗体背景新解
  在Form中添加Image控件
   设BMP图象
   name为 IMG_BK
   在Foem的Create事件中写入
   Self.brush.bitmap:=img_bk.picture.bitmap;

2.在标题栏处画VCL控件(一行解决问题!!!)
   在 form 的onpaint 事件中
   控件.pointto(getdc(0),left,top);

3 Edit 中只输入数字
    SetWindowLong(Edit1.Handle, GWL_STYLE,
                  GetWindowLong(Edit1.Handle, GWL_STYLE) or
                  ES_NUMBER);
4.类似MDI方式新解
在要设置child的oncreate方式下写入:
           self.parent:='要设置为mainform的Form';

5. 屏幕的Refresh(只需一行!)
RedrawWindow(0,nil,0,RDW_ERASE or RDW_INVALIDATE or RDW_ALLCHILDREN);
                |     |
               ---   ----
             handle  RGN(可刷新局部屏幕)
6.类似DOS下的CLS指令的WINDOWS指令!
  paintdesktop(getdc(0));

7.扩展控件新功能
   在编程中 ,我们经常要控制控件的动作,但该控件又没有提供该方法

   这时 ,可通过发消息给该控件 ,以达到我们的目的!

   如:
      button1.perform(wm_keydown,13,0);

      listbox1.perform(wm_vscroll,sb_linedown,0);

   等等   可少去 重载之苦!!!!!

8.闪烁标题如打印机超时(一行)
form 放一timer 控件

        time 事件  中 写入 ;

             flashwindow(application.handle,true);


9.在桌面上加个VCL控件!(不是画的,不可refresh)
  windows.setparent(控件.handle,0);

注: 想放哪都行  (如'开始处状态栏')


10.关于  '类似MDI方式新解(一行就行!!!!)'的修正
  windows.setparent(self.handle,'要设置为mainform的Form');

11 普通Form象MDI中mainform始终在最底层
        SetActiveWindow(0);
   或  SetwindowPos(...);
12 执行下列语句开始Windows屏幕保护程序
   SendMessage(HWND_BROADCAST,WM_SYSCOMMAND,SC_SCREENSAVE,0);
13 button 的 caption 多行显示:
   SetWindowLong(Button1.handle, GWL_STYLE,
                 GetWindowlong(Button1.Handle, GWL_STYLE) or
                 BS_MULTILINE);
   必要时加上 Button1.Invalidate;

14.整死windows98 :)
   asm int $19 end

 

Q: 怎么来改变ListBox的字体呢?就修改其中的一行。

A: 先把ListBox1.Style 设成lbOwnerDrawFixed
然后在 OnDrawItem 事件下写下如下代码

procedure TForm1.ListBox1DrawItem(Control: TWinControl; Index: Integer;
 Rect: TRect; State: TOwnerDrawState);
var
 Offset: Integer;
begin
 Offset := 2;
 with (Control as TListBox).Canvas do begin
   FillRect(Rect);
   if Index = 2 then begin
     Font.Name := 'Fixedsys';
     Font.Color := clRed;
     Font.Size := 12;
   end else begin
     Font.Name := 'Arial';
     Font.Color := clBlack;
     Font.Size := 8;
   end;
   if odSelected in State then begin
     Font.Color := clWhite;
   end;
   TextOut(Rect.Left + Offset, Rect.Top, (Control as TListBox).Items[Index]);
 end;
end;


Q:怎么在RichEdit里面插入图片?

A: 请到这里来看看会找到答案

http://www.undu.com/Articles/991107c.html


Q:怎么才能目录呢?

A:我来。

uses ShellAPI;

procedure DeleteFiles(Source: string);
var
  FO: TShFileOpStruct;
begin
  FillChar(FO,SizeOf(FO),#0);
  FO.Wnd := Form1.Handle;
  FO.wFunc := FO_DELETE;
  FO.pFrom := PChar(Source);
  ShFileOperation(FO);
end;

procedure EmptyDirectory(Path: String);
begin
    if DirectoryExists(Path) then
    begin
         DeleteFiles(Path+'/*');
    end
    else
        ForceDirectories(Path);
end;

Q:如何映射网络驱动器?

比如我要把//Server/sys映射为F盘。我需要一个函数比如

给出输入参数为//server/sys/home/bruno给我的返回值是F:/home/bruno

A:

Function UNCToDrive(UNCPath: STring): STring;
var
  DriveNum: Integer;
  DriveChar: Char;
  DriveBits: set of 0..25;
  StartSTr,TestStr: STring;
begin
  result := UNCPath;
  StartSTr := UNCPath;
  Integer(DriveBits) := GetLogicalDrives;
  for DriveNum := 0 to 25 do
  begin
    if (DriveNum in DriveBits) then begin
      DriveChar := Char(DriveNum + Ord('A'));
      TestSTr := ExpandUNCFileName(DriveChar+':/');
      If TEstStr <> '' then
        If Pos(Uppercase(TestSTr),Uppercase(STartSTr)) > 0 then
           begin
              Delete(StartSTr,1,Length(TestSTr));
              result := DriveChar+':/'+StartSTr;
              break;
           end;
        end;
  end;
end;


Q:我有一些特殊语言的字体来用,它们存储在我的EXE文件里,但是两点。

   * 我不想放到font文件夹里
   * 我不想从EXE文件里面提取出来

如果可能,请告诉我。

因为,我的字体是自己做的不是windows自带的,我想保护自己的东西。

A:不太可能,必须提取出来。你可以使用这个保护过程来保护你的文件不被修改和删除。

在EXE执行的时候把字体放到临时文件夹里,结束的时候删除它。

function ProtectFile(sFilename : string) : hFile;
var
       hf: hFile;
       lwHFileSize, lwFilesize: longword;
       ofs : TOFStruct;
begin
       if FileExists(sFilename) then
       begin
               hf := OpenFile(pchar(sFilename), ofs, OF_READ or OF_WRITE or OF_SHARE_EXCLUSIVE);
               if hf <> 0 then
               begin
                       lwFilesize := GetFileSize(hf, @lwHFileSize);
                       if LockFile(hf, 0, 0, lwFilesize, lwHFilesize) then
                       Result := hf else Result := 0;
               end
               else Result := 0;
       end
       else Result := 0;
end;

//..
var
 ResS: TResourceStream;
 TempPath: array [0..MAX_PATH] of Char;
 TempDir: string;
begin
 GetTempPath(Sizeof(TempPath), TempPath);
 TempDir := StrPas(Path);
 ResS := TResourceStream.Create(hInstance, 'SOME_FONT', 'RT_FONT');
 ResS.SavetoFile(TempDir+'some_font.ttf');
 ResS.Free;
 AddFontResource(TempDir+'some_font.ttf');
 SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
 ProtectFile(TempDir+'some_font.ttf');
end;


Q:如何得到当前的ProgramFiles得路径?

A:用读写注册表的方法就可以做到。

代码如下:

uses registry;

procedure TForm1.Button1Click(Sender: TObject);
var
 reg:TRegistry;
begin
 reg:=TRegistry.Create;
 reg.RootKey:=HKEY_LOCAL_MACHINE;
 if reg.OpenKey('SOFTWARE/Microsoft/Windows/CurrentVersion',false) then
 begin
   edit1.Text:=reg.ReadString('ProgramFilesDir');
   reg.CloseKey;
   reg.Free;
 end;
end;


Q:如何在Jpg图像上写上字?

A:这里有个代码。

hmm, here's a sample with help of Bitmap, you can chance the brush style of canvas to bsClear to make the text transparent


uses
 Jpeg;

procedure TForm1.Button1Click(Sender: TObject);
var
 Bmp : TBitmap;
 Jpg : TJpegImage;
begin
 try
   Bmp := TBitmap.Create;
   Jpg := TjpegImage.Create;
   Jpg.LoadFromFile('c:/img.jpg');
   Bmp.Assign(Jpg);
   Bmp.Canvas.Brush.Style := bsClear;
   Bmp.Canvas.Font.Color := clYellow;
   Bmp.Canvas.TextOut(10,10,'Hello World');
   Jpg.Assign(Bmp);
   Jpg.SaveToFile('c:/img2.jpg');
 finally
   bmp.Free;
   jpg.Free;
 end;
end;

Q:怎么用delphi修改文件的时间呢?

在windows下,属性里面有三个日起,创建,修改,存储。我怎么来修改啊?

A:Here is the excerpt from the Jedi Code Library. If it is not complete then get the JCL.

type
 // indicates the file time to set, used by SetFileTimesHelper and SetDirTimesHelper
 TFileTimes = (ftLastAccess, ftLastWrite, ftCreation);

function SetFileTimesHelper(const FileName: string; const DateTime: TDateTime; Times: TFileTimes): Boolean;
var
 Handle: THandle;
 FileTime: TFileTime;
 SystemTime: TSystemTime;
begin
 Result := False;
 Handle := CreateFile(PChar(FileName), GENERIC_WRITE, FILE_SHARE_READ, nil,
   OPEN_EXISTING, 0, 0);
 if Handle <> INVALID_HANDLE_VALUE then
 try
   //SysUtils.DateTimeToSystemTime(DateTimeToLocalDateTime(DateTime), SystemTime);
   SysUtils.DateTimeToSystemTime(DateTime, SystemTime);
   if Windows.SystemTimeToFileTime(SystemTime, FileTime) then
   begin
     case Times of
       ftLastAccess:
         Result := SetFileTime(Handle, nil, @FileTime, nil);
       ftLastWrite:
         Result := SetFileTime(Handle, nil, nil, @FileTime);
       ftCreation:
         Result := SetFileTime(Handle, @FileTime, nil, nil);
     end;
   end;
 finally
   CloseHandle(Handle);
 end;
end;

//--------------------------------------------------------------------------------------------------

function SetFileLastAccess(const FileName: string; const DateTime: TDateTime): Boolean;
begin
 Result := SetFileTimesHelper(FileName, DateTime, ftLastAccess);
end;

//--------------------------------------------------------------------------------------------------

function SetFileLastWrite(const FileName: string; const DateTime: TDateTime): Boolean;
begin
 Result := SetFileTimesHelper(FileName, DateTime, ftLastWrite);
end;

//--------------------------------------------------------------------------------------------------

function SetFileCreation(const FileName: string; const DateTime: TDateTime): Boolean;
begin
 Result := SetFileTimesHelper(FileName, DateTime, ftCreation);
end;


google上的有关delphi得网址:

http://directory.google.com/Top/Computers/Programming/Languages/Delphi/?tc=1

yahoo上有关delphi得网址

http://dir.yahoo.com/Computers_and_Internet/Programming_and_Development/Languages/Delphi/


删掉程序自己的exe文件
procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
var
  F:TextFile;
begin
  AssignFile(F,'delself.bat');
  Rewrite(F);{F为TextFile类型}
  WriteLn(F,'del '+ExtractFileName(Application.ExeName));
  WriteLn(F,'del %0');   //删除自己delself.bat
  CloseFile(F);
  WinExec('delself.bat',SW_HIDE);
end;


if ord(s[9])>128 then
  ShowMessage('该位置字符是汉字');
汉字是双字节的
更改系统时间格式:

var
  str: string;
begin
  str := 'yyyy-mm-dd';
  if SetLocaleInfoa(LOCALE_SYSTEM_DEFAULT, LOCALE_SLONGDATE, PChar(str)) then
  begin
    showmessage('更改日期格式成功');
  end;
end;

休息一分钟:
var
I:integer;
begin
  i:=gettickcount;
  while (Gettickcount-i)<=10000 do
    application.ProcessMessages;//保证消息循环
end;

 


取主文件名:
function retuFileName(const FileName: string): string;
var
  I: Integer;
begin
  I := LastDelimiter('.', FileName);
  Result := Copy(FileName, 1, i-1);

end;

 

 

(1).按下ctrl和其它键之后发生一事件。
    procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    begin
      if (ssCtrl in Shift) and (key =67) then
         showmessage('keydown Ctrl+C');
    end;
(2).Dbgrid中用Enter键代替Tab键.
   procedure TForm1.DBGrid1KeyPress(Sender: TObject; var Key: Char);
   begin
     if Key = #13 then
     if ActiveControl = DBGrid1 then
     begin
        TDBGrid(ActiveControl).SelectedIndex := TDBGrid(ActiveControl).SelectedIndex + 1;
        Key := #0;
     end;
   end;
(3).Dbgrid中选择多行发生一事件。
    procedure TForm1.Button1Click(Sender: TObject);
    var
    i:integer;
    bookmarklist:Tbookmarklist;
    bookmark:tbookmarkstr;
    begin
      bookmark:=adoquery1.Bookmark;
      bookmarklist:=dbgrid1.SelectedRows;
      try
      begin
        for i:=0 to bookmarklist.Count-1 do
        begin
          adoquery1.Bookmark:=bookmarklist[i];
          with adoquery1 do
          begin
            edit;
            fieldbyname('mdg').AsString:=edit2.Text;
            post;
          end;
        end;
      end;
      finally
      adoquery1.Bookmark:=bookmark;
      end;
    end;
(4).Form的一个出现效果。
    procedure TForm1.Button1Click(Sender: TObject);
    var
    r:thandle;
    i:integer;
    begin
      for i:=1 to trunc(width/1.414) do
      begin
        r:=CreateEllipticRgn(trunc(width/2)-i,trunc(height/2)-i,trunc(width/2)+i,trunc(height/2)+i);
        SetWindowRgn(handle,r,true);
        Application.ProcessMessages;
        sleep(1);
      end;
    end;
(5).用Enter代替Tab在编辑框中移动隹点。
    procedure TForm1.FormKeyPress(Sender: TObject; var Key: Char);
    begin
      if key=#13 then
        begin
          if not (Activecontrol is Tmemo) then
          begin
            key:=#0;
            keybd_event(vk_tab,mapvirtualkey(vk_tab,0),0,0);
          end;
        end;
    end;
(6).Progressbar加上色彩。
    const
    {$EXTERNALSYM PBS_MARQUEE}
    PBS_MARQUEE = 08;
    var
      Form1: TForm1;
    implementation
    {$R *.dfm}
    uses
    CommCtrl;
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      // Set the Background color to teal
      Progressbar1.Brush.Color := clTeal;
      // Set bar color to yellow
      SendMessage(ProgressBar1.Handle, PBM_SETBARCOLOR, 0, clYellow);
    end;
(7).住点移动时编辑框色彩不同。
    procedure TForm1.Edit1Enter(Sender: TObject);
    begin
      (sender as tedit).Color:=clred;
    end;
    procedure TForm1.Edit1Exit(Sender: TObject);
    begin
      (sender as tedit).Color:=clwhite;
    end;
(8).备份和恢复
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      if OpenDialog1.Execute then
      begin
        try
          adoconnection1.Connected:=False;
          adoconnection1.ConnectionString:='Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=master;Data Source=FRIEND-YOFZKSCO;'+
          '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';
          adoconnection1.Connected:=True;
          with adoQuery1 do
          begin
            Close;
            SQL.Clear;
            SQL.Add('Backup DataBase sfa to disk ='''+opendialog1.FileName+'''');
            ExecSQL;
          end;
        except
          ShowMessage('±?·Y꧰ü');
        Exit;
        end;
      end;
      Application.MessageBox('1§?2?ú£?êy?Y±?·Y3é1|','ìáê?',MB_OK + MB_ICONINFORMATION);
    end;
    procedure TForm1.Button2Click(Sender: TObject);
    begin
      if OpenDialog1.Execute then
      begin
        try
          adoconnection1.Connected:=false;
          adoconnection1.ConnectionString:='Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=master;Data Source=FRIEND-YOFZKSCO;'+
          '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';
          adoconnection1.Connected:=true;
          with adoQuery1 do
          begin
            Close;
            SQL.Clear;
            SQL.Add('Restore DataBase sfa from disk ='''+opendialog1.FileName+'''');
            ExecSQL;
         end;
       except
         ShowMessage('???′꧰ü');
         Exit;
       end;
     end;
     Application.MessageBox('1§?2?ú£?êy?Y???′3é1|','ìáê?',MB_OK + MB_ICONINFORMATION);
    end;


(9).查找局域网上的sqlserver报务器。
    uses Comobj;
    procedure TForm1.Button1Click(Sender: TObject);
    var
    SQLServer:Variant;
    ServerList:Variant;
    i,nServers:integer;
    sRetValue:String;
    begin
      SQLServer := CreateOleObject('SQLDMO.Application');
      ServerList:= SQLServer.ListAvailableSQLServers;
      nServers:=ServerList.Count;
      for i := 1 to nservers do
      ListBox1.Items.Add(ServerList.Item(i));
      SQLServer:=NULL;
      serverList:=NULL;
    end;
(10).窗体打开时的淡入效果。
    procedure TForm1.FormCreate(Sender: TObject);
    begin
      AnimateWindow (Handle, 400, AW_CENTER);
    end;
(11).动态创建窗体。
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      try
        form2:=Tform2.Create(self);
        form2.ShowModal;
      finally
        form2.Free;
      end;
    end;
    procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
    begin
      action:=cafree;
    end;
    procedure TForm1.FormDestroy(Sender: TObject);
    begin
      form1:=nil;
    end;
(12).复制文件。
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      try
      copyfileA(pchar('C:/AAA.txt'),pchar('D:/AAA.txt'),false);
      except
      showmessage('sfdsdf');
      end;
    end;
(13).复制文件夹。
    uses shellAPI;
    procedure TForm1.Button1Click(Sender: TObject);
    var
       lpFileOp: TSHFileOpStruct;
    begin
      with lpFileOp do
      begin
        Wnd:=Self.Handle;
        wfunc:=FO_COPY;
        pFrom:=pchar('C:/AAA');
        pTo:=pchar('D:/AAA');
        fFlags:=FOF_ALLOWUNDO;
        hNameMappings:=nil;
        lpszProgressTitle:=nil;
        fAnyOperationsAborted:=True;
     end;
     if SHFileOperation(lpFileOp)<>0 then
     ShowMessage('删除失败');
    end;
(14).改变Dbgrid的选定色。
    procedure TForm1.DBGrid1DrawDataCell(Sender: TObject; const Rect: TRect;
    Field: TField; State: TGridDrawState);
    begin
      if gdSelected in state then
      SetBkColor(dbgrid1.canvas.handle,clgreen)
      else
      setbkcolor(dbgrid1.canvas.handle,clwhite);
      dbgrid1.Canvas.TextRect(rect,0,0,field.AsString);
      dbgrid1.Canvas.Textout(rect.Left,rect.Top,field.AsString);
    end;
(15).检测系统是否已安装了ADO。
    uses registry;
    function Tform1.ADOInstalled:Boolean;
    var
    r:TRegistry;
    s:string;
    begin
      r := TRegistry.create;
      try
      with r do
      begin
        RootKey := HKEY_CLASSES_ROOT;
        OpenKey( '/ADODB.Connection/CurVer', false );
        s := ReadString('');
        if s <> '' then Result := True
        else Result := False;
        CloseKey;
      end;
      finally
       r.free;
      end;
    end;
    procedure TForm1.Button1Click(Sender: TObject);
    begin
     if ADOInstalled then showmessage('this computer has installed ADO');
    end;
(16).取利主机的ip地址。
    uses winsock;
    procedure TForm1.Button1Click(Sender: TObject);
    var
    IP:string;
    IPstr:String;
    buffer:array[1..32] of char;
    i:integer;
    WSData:TWSAdata;
    Host:PHostEnt;
    begin
      if WSAstartup(2,WSData)<>0 then
      begin
        showmessage('WS2_32.DLL3?ê??ˉ꧰ü.');
        exit;
      end;
      try
        if GetHostname(@buffer[1],32)<>0 then
        begin
          showmessage('??óDμ?μ??÷?ú??.');
        exit;
      end;
      except
        showmessage('??óD3é1|·μ???÷?ú??');
        exit;
      end;
      Host:=GetHostbyname(@buffer[1]);
      if Host=nil then
      begin
        showmessage('IPμ??·?a??.');
        exit;
      end
      else
      begin
        edit2.Text:=Host.h_name;
        edit3.Text:=chr(host.h_addrtype+64);
        for i:=1 to 4 do
        begin
         IP:=inttostr(ord(host.h_addr^[i-1]));
         if i<4 then
         ipstr:=ipstr+IP+'.'
        else
         edit1.Text:=ipstr+ip;
        end;
       end;
       WSACleanup;
    end;
(17).取得计算机名。
    function tform1.get_name:string;
    var  ComputerName: PChar;  size: DWord;
    begin
        GetMem(ComputerName,255);
        size:=255;
        if GetComputerName(ComputerName,size)=False then
           result:=''
        else
           result:=ComputerName;
        FreeMem(ComputerName);
    end;
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      label1.Caption:=get_name;
    end;


(18).取得硬盘序列号。
    function tform1.GetHDSerialNumber: LongInt;
    {$IFDEF WIN32}
    var
      pdw : pDWord;
      mc, fl : dword;
    {$ENDIF}
    begin
      {$IfDef WIN32}
      New(pdw);
      GetVolumeInformation('c:/',nil,0,pdw,mc,fl,nil,0);
      Result := pdw^;
      dispose(pdw);
     {$ELSE}
      Result := GetWinFlags;
      {$ENDIF}
    end;
    procedure TForm1.Button1Click(Sender: TObject);
    begin
      edit1.Text:=inttostr(gethdserialnumber);
    end;
(19).限定光标移动范围。
    procedure TForm1.Button1Click(Sender: TObject);
    var
    rect1:trect;
    begin
      rect1:=button2.BoundsRect;
      mapwindowpoints(handle,0,rect1,2);
      clipcursor(@rect1);
    end;
    procedure TForm1.Button2Click(Sender: TObject);
    var
    screenrect:trect;
    begin
      screenrect:=rect(0,0,screen.Width,screen.Height);
      clipcursor(@screenrect);
    end;
(20).限制edit框只能输入数字。
    procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
    begin
      if not (key in ['0'..'9','.',#8]) then
      begin
        key:=#0;
        Messagebeep(0);
      end;
    end;
(21).dbgrid中根据任一条件某一格变色。
    procedure TForm_main.DBGridEh1DrawColumnCell(Sender: TObject;
    const Rect: TRect; DataCol: Integer; Column: TColumnEh;
    State: TGridDrawState);
    begin
      if (trim(DataModule1.ADOQuery1.FieldByName('dczt').AsString)='OK') then
      begin
        if datacol=6 then
        begin
          DbGrideh1.Canvas.Brush.Color:=clGradientActiveCaption;
          DbGrideh1.DefaultDrawColumnCell(Rect,datacol,column,state);
        end;
      end;
    end;
(22).打开word文件。
    procedure TfjfsglForm.SpeedButton4Click(Sender: TObject);
    var
    MSWord: Variant;
    str:string;
    begin
      if trim(DataModule1.adoquery27.fieldbyname('fjmc').asstring)<>'' then
      begin
        str:=trim(DataModule1.ADOQuery27.fieldbyname('fjmc').AsString);
        MSWord:= CreateOLEObject('Word.Application');//
        MSWord.Documents.Open('d:/Program Files/Common Files/Sfa/'+str, True);//
        MSWord.Visible:=1;//
        str:='';
        MSWord.ActiveDocument.Range(0, 0);//
        MSWord.ActiveDocument.Range.InsertAfter(str);//?úWord?D???ó×?·?'Title'
        MSWord.ActiveDocument.Range.InsertParagraphAfter;
      end
      else
      showmessage('');
    end;
(23).word文件传入和传出数据库。
    uses IdGlobal;
    procedure TdjhyForm.SpeedButton2Click(Sender: TObject);
    var
    sfilename:string;
    function BlobContentTostring(const Filename:string):string;
    begin
      with Tfilestream.Create(filename,fmopenread)  do
      try
        setlength(result,size);
        read(pointer(result)^,size);
      finally
        free;
      end;
    end;
    begin
      if opendialog1.Execute then
      begin
        sfilename:=opendialog1.FileName;
        DataModule1.ADOQuery14.Edit;
        DataModule1.ADOQuery14.FieldByName('word').AsString:=blobcontenttostring(sfilename);
        DataModule1.ADOQuery14.Post;
      end;
    end;
    procedure TdjhyForm.SpeedButton1Click(Sender: TObject);
    var
    sfilename:string;
    bs:Tadoblobstream;
    begin
      bs:=Tadoblobstream.Create(TBLOBfield(DataModule1.ADOQuery14.FieldByName('word')),bmread);
      try
        sfilename:=extractfilepath(application.ExeName)+trim(DataModule1.adoquery14.fieldbyname('hybh').AsString);
        sfilename:=sfilename+'.'+'doc';
        bs.SaveToFile(sfilename);
        try
          djhyopenform:=Tdjhyopenform.Create(self);
          djhyopenform.olecontainer1.CreateObjectFromFile(sfilename,false);
          djhyopenform.OleContainer1.Iconic:=true;
          djhyopenform.ShowModal;
        finally
          djhyopenform.Free;
        end;
      finally
        bs.free;
      end;
    end;
(24).中文标题的提示框。
    procedure TdjhyForm.SpeedButton5Click(Sender: TObject);
    begin
      if Application.MessageBox('', Mb_YesNo + Mb_IconWarning) =Id_yes then DataModule1.ADOQuery14.Delete;
    end;
(25).运行一应用程序文件。
    WinExec('HH.EXE D:/Program files/common files/MyshipperCRM e-sales help/MyshipperCRM e-sales help.chm',SW_NORMAL);

问:如何避免同时运行多个相同程序?
答:为了避免同时运行多个程序的副本(节约系统资源也),程序一般会弄成每次只能运行一个.这又有几种方法.
一种方法是程序运行时先查找有没有相同的运行了,如果有,就立刻退出程序.
修改dpr项目文件,修改begin和end之间的代码如下:
begin
Application.Initialize;
if FindWindow('TForm1','Form1')=0 then begin
//当没有找到Form1时执行下面代码
Application.ShowMainForm:=False; //不显示主窗口
Application.CreateForm(TForm1, Form1);
Application.Run;
end;
end.
另一种方法是启动时会先通过窗口名来确定是否已经在运行,如果是则关闭原先的再启动。“冰河”就是用这种方法的。
这样做的好处在于方便升级.它会自动用新版本覆盖旧版本.
方法如下:修改dpr项目文件
uses
Forms,windows,messages,
Unit1 in 'Unit1.pas' {Form1};

 

问:如何能使程序能在windows启动时自动启动?
答:为了程序能在Windows每次启动时自动运行,可以通过六种途径来实现.“冰河”用注册表的方式。
加入Registry单元,改写上面的窗口Create事件,改写后的程序如下:
procedure TForm1.FormCreate(Sender: TObject);
const K = '/Software/Microsoft/Windows/CurrentVersion/RunServices';
var myname: string;
begin
{Write by Lovejingtao,http://Lovejingtao.126.com,Lovejingtao@21cn.com}
myname := ExtractFilename(Application.Exename); //获得文件名
if application.Exename <> GetWindir + myname then //如果文件不是在Windows/System/那么..
begin
copyfile(pchar(application.Exename), pchar(GetWindir + myname), False);{//将自己拷贝到Windows/System/下}
Winexec(pchar(GetWindir + myname), sw_hide);//运行Windows/System/下的新文件
application.Terminate;//退出
end;
with TRegistry.Create do
try
RootKey := HKEY_LOCAL_MACHINE;
OpenKey( K, TRUE );
WriteString( 'syspler', application.ExeName );
finally
free;
end;
end;


问:怎么才能把自己的程序删除掉?
答:很简单,可以写一个BAT文件
例如:a.bat
     del %0
这样就把a.bat删除掉了!

放一个例子:
用过DOS的朋友应该还记得批处理文件吧,新建一个批处理文件a.bat,编辑其内容为:del %0,然后运行它,怎么样?a.bat把自己删除掉了!!!好,我们就用它来进行程序的“自杀”!
找一个EXE可执行文件,比如说abc.exe,新建一个批处理文件a.bat,编辑其内容为:
:pp
del abc.exe
if exist abc.exe goto pp
del %0
先运行abc.exe,再运行a.bat,然后将abc.exe退出,你会发现a.exe和a.bat都没有了!!!按照这个思路,我们可以在程序中根据文件名称写一个批处理,将上面的abc.exe换成自己的EXE文件名就可以了。运行Delphi,新建一个工程,添加一个Button到窗体上,点击Button,写下如下代码:

procedure TForm1.Button1Click(Sender: TObject);
var Selfname,BatFilename,s1,s2:string;
BatchFile: TextFile;
begin
Selfname:=Extractfilename(application.exename);//取EXE文件自己的名称
BatFilename:=ExtractFilePath(Application.ExeName)+ 'a.bat';//批处理文件名称
S1:='@del '+Selfname;
S2:='if exist '+Selfname+' goto pp';
assignfile(BatchFile,BatFilename);
rewrite(BatchFile);
writeln(BatchFile,':pp');
writeln(BatchFile,S1);
writeln(BatchFile,S2);
writeln(BatchFile,'@del %0');
closefile(BatchFile);
winexec(pchar(BatFilename),sw_hide);//隐藏窗口运行a.bat
application.Terminate;//退出程序
end;
那我们的事情是不是就完了?NO!上面的程序原理是对的,但如果你的程序是运行在系统目录下如Windows目录下或者Windows/System等目录下,除非你打开那个目录看着它删除,否则根本没法卸掉的。那怎么办?别急,我们请出一个函数CreateProcess,它的原型为:
BOOL CreateProcess(
LPCTSTR lpApplicationName, // pointer to name of executable module
LPTSTR lpCommandLine, // pointer to command line string
LPSECURITY_ATTRIBUTES lpProcessAttributes, // pointer to process security attributes
LPSECURITY_ATTRIBUTES lpThreadAttributes, // pointer to thread security attributes
BOOL bInheritHandles, // handle inheritance flag
DWORD dwCreationFlags, // creation flags
LPVOID lpEnvironment, // pointer to new environment block
LPCTSTR lpCurrentDirectory, // pointer to current directory name
LPSTARTUPINFO lpStartupInfo, // pointer to STARTUPINFO
LPPROCESS_INFORMATION lpProcessInformation // pointer to PROCESS_INFORMATION
);
这个函数和OpenProcess、ReadProcessMemory、WriteProcessMemory使用可以用来读取和修改内存数据,常用的游戏修改器就是用它。由于这些不是本文的重点所以这里不作详细介绍,感兴趣的读者可自行翻阅Delphi自带的帮助文件。用CreateProcess函数创建一个进程就可以完美的完成我们的“程序自杀”了。
运行Delphi,新建一个工程,添加一个Button到窗体上,全部代码如下:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure My_DeleteMe; //自定义程序自杀过程
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
begin
My_DeleteMe;
end;
procedure TForm1.My_DeleteMe; //程序自杀
//-----------------------------------------------------------
function GetShortName(sLongName: string): string; //转换长文件名
var
sShortName: string;
nShortNameLen: integer;
begin
SetLength(sShortName, MAX_PATH);
nShortNameLen := GetShortPathName(PChar(sLongName),
PChar(sShortName), MAX_PATH - 1);
if (0 = nShortNameLen) then
begin
// handle errors...
end;
SetLength(sShortName, nShortNameLen);
Result := sShortName;
end;
//-------------------------------------------------
var
BatchFile: TextFile;
BatchFileName: string;
ProcessInfo: TProcessInformation;
StartUpInfo: TStartupInfo;
begin
BatchFileName := ExtractFilePath(ParamStr(0)) + '$$a$$.bat';
AssignFile(BatchFile, BatchFileName);
Rewrite(BatchFile);
Writeln(BatchFile, ':try');
Writeln(BatchFile, 'del "' + GetShortName(ParamStr(0)) + '"');
Writeln(BatchFile, 'if exist "' + GetShortName(ParamStr(0)) + '"' + ' goto try');
Writeln(BatchFile, 'del %0');
Writeln(BatchFile, 'cls');
Writeln(BatchFile, 'exit');
CloseFile(BatchFile);
FillChar(StartUpInfo, SizeOf(StartUpInfo), $00);
StartUpInfo.dwFlags := STARTF_USESHOWWINDOW;
StartUpInfo.wShowWindow := SW_Hide;
if CreateProcess(nil, PChar(BatchFileName), nil, nil,
False, IDLE_PRIORITY_CLASS, nil, nil, StartUpInfo,
ProcessInfo) then
begin
CloseHandle(ProcessInfo.hThread);
CloseHandle(ProcessInfo.hProcess);
end;
Application.Terminate;
end;
end.

补充:1、上面的批处理的 del %0等同于 del a.bat,用del a.bat则批处理文件必须为a.bat,用del %0则可以随意。
2、所有程序在Pwin98+Delphi5、Win2000+Delphi5下运行通过。
本文的标题为《安装与卸载之卸载篇》,下次将介绍如何用Delphi制作自己的安装程序。记得有一位著名的黑客说过:我从来不去找什么工具软件,需要的话就自己写一个。如果我们也持这种态度,则编程水平一定会越来越高。

问:如何得到*******中的密码?
答:这里有一个例子:
//***********************************************************8
//password_dos.dpr,陈经韬作品
//http://lovejingtao.126.com
//lovejingtao@21cn.com
//***********************************************************8

program password_dos;
{$apptype console} //设置程序为非图形界面

uses
windows,
messages;

const s:boolean=true;//置循环标志

var

pass_edit_hwnd:hwnd;//密码窗口句柄
p:tpoint; //鼠标指针

begin

writeln;
writeln('**************************************************************************');
writeln;
writeln;
writeln('     星号*密码破解器'                                             );
writeln('     使用方法:将鼠标移动到密码框,密码就会自动现形!'               );
writeln('     按 Ctrl+C 退出程序。 '                                       );
writeln('                               
///|/// '                         );
writeln('                               // - - // '                        );
writeln('                                ( @ @ ) '                         );
writeln('      +----------------------oOOo-(_)-oOOo---------------------+ ');
writeln('      |                                                        | ');
writeln('      | 若在使用过程中发现任何问题或有新的想法请及时与我联系:  | ');
writeln('      | 主页:http://lovejingtao.126.com                        | ');
writeln('      | E-MAIL:
lovejingtao@21cn.com                           | ');
writeln('      |                                                        | ');
writeln('      |                               Oooo 陈经韬 2000.07      | ');
writeln('      +---------------------- oooO---(   )---------------------+ ');
writeln('                              (   )   ) / '                       );
writeln('                               / (   (_/ '                        );
writeln('                                /_) '                             );
writeln;
writeln('**************************************************************************');
writeln;
while s<>false do begin
getcursorpos(p); //查鼠标坐标
pass_edit_hwnd:= WindowFromPoint(p); //返回句柄
SendMessage(pass_edit_hwnd,EM_SETPASSWORDCHAR,0,0);//发送消息
SendMessage(pass_edit_hwnd,WM_PAINT,0,0); //
SendMessage(pass_edit_hwnd,WM_KILLFOCUS,0,0); // 刷新窗口
SendMessage(pass_edit_hwnd,WM_SETFOCUS,0,0); //
sleep(1000); //延时1000毫秒
end;
end.


问:如何对注册进行操作?
答:首先:uses registry;
var
  r:TRegistry
r:=Tregistry.Create;
r.RootKey:=HKEY_LOCAL_MACHINE、HKEY_CURRENT_USER 之类
r.OpenKey('Software/microsoft'之类, true);
然后就可以 r.ReadString 、 r.ReadInteger、r.WriteString 、 r.WriteInteger 之类
r.Free;


问:怎么使用ini文件进行一些设置的保存?
答:其实很简单,在uses中加入INIFiles然后可以在form的onCreate和onClose两个事件中写东西,onCreate是读出以前写的内容,onClose是写入更改过的内容,下面是一个例子:
放一个CheckBox和Edit

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ComCtrls,INIFiles;//INIFiles不要忘了加

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  With TINIFile.Create('a.ini') do//创建a.ini
    begin
    WriteBool('MySetting', 'CheckBox1_Checked', CheckBox1.Checked);{保存到MySetting下面的CheckBox1_Checked子键下,然后把Checkbox1的是否按下状态写进去}
    WriteString('MySetting', 'Edit1_Text', Edit1.Text);//同上
    end;
end;

procedure TForm1.FormCreate(Sender: TObject);//读入a.ini文件中的设置
begin
  With TINIFile.Create('a.ini') do//打开已创建的a.ini
    begin
    CheckBox1.Checked := ReadBool('MySetting', 'CheckBox1_Checked', False);{同上面的写入一样,这里是读取ReadBool和WriteBool是两个BOOL值的写入方法.}
    Edit1.Text := ReadString('MySetting', 'Edit1_Text', '');//同上
    end;
end;


问:如何能使一个正在运行的程序自动最大化?
答:这是一个例子:
var
hwndwindow:hwnd;
begin
hwndwindow:=findwindow(nil,'DELPHI技巧');//DELPHI技艺改成你要最大化的窗口标提.
if hwndwindow<>0 then//不等于0则是找到了这个窗体
postmessage(hwndwindow,WM_SYSCOMMAND,SC_MAXIMIZE,0);//用postmessage发送一条最大化消息(SC_MAXIMIZE)到这个窗体的句柄
//******************************************************
//另外postmessage(hwndwindow,wm_close,0,0);为关闭
//如果需要要自己的程序中使程序动态变最大化则用
form1.windowstate:=wsmaximized; //form1为你要最大化的窗口名!
//几个要用到的名词:
1.hwnd是句柄的意思,只有先得到了窗体的句柄才能控制它
2.findwindow是找窗体的意思
3.nil是空指针的意思
4.postmessage发送一条消息给一个已找到的窗口句柄.

问:如何使程序在执行过程中暂停一段时间?
答:要使在运行中的程序暂停一段时间可以使用sleep这个关键词,下面是一个例子
procedure TForm1.Button1Click(Sender: TObject);
var
h,m,s,ms:word;
begin
Edit1.text:=DateTimeToStr(now);
sleep(2000);//2000就表示2个微秒
edit2.text:=DateTimeToStr(now);
DecodeTime(strtodatetime(edit2.text)-strtodatetime(edit1.text),h,m,s,ms);
showmessage(format('小时:%d',[h])+format('分钟:%d',[m])+format('秒:%d',[s])+format('微秒:%d',[ms]));
end;
//另外,这也是一个很好的时间相减例子
报告时间的例子:
//先定义:
var
Present: TDateTime;//定义成日期和时间
begin
Year, Month, Day, Hour, Min, Sec, MSec: Word;//定义年月日小时分种秒微秒
DecodeTime(Present, Hour, Min, Sec, MSec);//提出小时分种秒微秒,以TDataTime方式
DecodeDate(Present, Year, Month, Day);//提出年月日,以TDataTime方式
Label1.Caption := 'Today is Day ' + IntToStr(Day) + ' of Month '
    + IntToStr(Month) + ' of Year ' + IntToStr(Year);//显示
Label2.Caption := 'The time is Minute ' + IntToStr(Min) + ' of Hour '
    + IntToStr(Hour);//显示
end;


问:如何在窗口上加入一个flash动画?
答:先把flash动画放到一个htm文件上,然后再把htm文件调用到窗口上例子如下:
procedure TForm1.FormCreate(Sender: TObject);
var
URL: OleVariant;
begin
URL := ExtractFilePath(Application.EXEName) + 'fla.htm';
Webbrowser1.Navigate2(URL);
end;
//要添加一下webbrowser控件

问:怎样才能在程序中实现跳转到网页?
答:例子如下:
procedure TForm1.ToolButton5Click(Sender: TObject);
begin
shellexecute(handle,nil,pchar('http://go.163.com/delphimyself'),nil,nil,sw_shownormal);
end;

问:怎样获得本程序的所在目录?
答:例子如下:
procedure TForm1.FormCreate(Sender: TObject);
begin
edit1.text:=ExtractFilePath(Application.EXEName);
end;
//ExtractFilePath(application.exename);是得到文件路径,application.exenane
//ExtractFilename(Application.Exename);是得到文件名,EXtractFilename


问:如何关闭windows?
答:这个可以关闭windows9X系统
exitwindowsex(ewx_shutdown,0);


问:如何获得windows的安装目录?
答:这里有一个例子:
procedure TForm1.Button1Click(Sender: TObject);
var     dir:array [0..255] of char;
begin
        GetWindowsDirectory(dir,255);
        edit1.Text:=strpas(dir);
end;
//先定义一个dir数组是char类型的
//然后getwindowsdirectory(dir,255);
//用strpas函数来显示出来
//还有一个例子也可以做到如下:
procedure TForm1.Button1Click(Sender: TObject);
var
winpath:pchar;
begin
getmem(winpath,255);
GetWindowsDirectory(winpath,255);
edit1.text:=winpath;
end;

***********************

判断是否item被选中:
for i:=0 to ListBox.Items.Count-1 do
 if ListBox.Selected[i] then
  begin
    showmessage('有item被选中');
    break;
  end
让第一项被选中: ListBox.ItemIndex:=0;

******************************
获取硬盘序列号

procedure TForm1.FormCreate(Sender: TObject);
var
dw,dwTemp1,dwTemp2:DWord;
p1,p2:array[0..30] of char;
begin
GetVolumeInformation(PChar('c:/'),p1,20,@dw,dwTemp1,dwTemp2,p2,20);
edit1.text:=inttohex(dw,8);//系列号
end;
 
***************************
在程序中拖动控件

在控件的mousedown中写入:

ReleaseCapture;
SendMessage(Panel1.Handle, WM_SYSCOMMAND, $F012, 0);
另外改变$F012的值会有很多别的功能
$F001:改变控件的left大小
$F002:改变控件的right大小
$F003:改变控件的top大小
$F004:改变控件的button大小
$F007:控件左边放大缩小
$F008:控件右边放大缩小
$F009:动态移动控件

************************
win98下隐藏进程方法

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation
function RegisterServiceProcess(dwProcessID,dwType: Integer): Integer; stdcall; external

'KERNEL32.DLL';

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
begin
  SetWindowLong(Application.Handle,GWL_EXSTYLE,WS_EX_TOOLWINDOW);
  RegisterServiceProcess(GetCurrentProcessID,1);
end;
end.
另外在dpr里面的Application.CreateForm(TForm1, Form1);后面加上
  Application.ShowMainForm := False;

**************************************
对某一个窗口发送鼠标消息
   SendMessage(Handle,WM_LBUTTONDBLCLK,0,0);
对系统发消息关闭程序
  SendMessage(Handle, WM_CLOSE, 0, 0);
启动开始菜单
  Sendmessage(Application.Handle,WM_SYSCOMMAND,SC_TASKLIST,0);

*****************************
日期时间类操作

showmessage(FormatDateTime('yyyy',now));//年
  showmessage(FormatDateTime('mm',now));  //月
  showmessage(FormatDateTime('dd',now));  //日
  showmessage(FormatDateTime('hh',now));  //时
  showmessage(FormatDateTime('nn',now));  //分
  showmessage(FormatDateTime('nn',now));  //秒
  showmessage(FormatDateTime('zzz',now)); //毫秒

*****************************
执行dos命令

winexec(pchar('net start w3svc '),sw_hide);
就是执行net start w3svc

****************************
Mediaplayer控件按纽控制

procedure TForm1.FormCreate(Sender: TObject);
begin
  MediaPlayer1.Open;
  MediaPlayer1.Play;
  MediaPlayer1.EnabledButtons:=[btPause, btStop, btNext, btPrev, btStep, btBack];
end;

procedure TForm1.MediaPlayer1Click(Sender: TObject; Button: TMPBtnType;
  var DoDefault: Boolean);
begin
  case Button of
    btPlay  :
      begin
        MediaPlayer1.Play;
        MediaPlayer1.EnabledButtons:=[btPause, btStop, btNext, btPrev, btStep, btBack];
      end;
    btPause :
      begin
        if MediaPlayer1.Mode=mpPaused then
        begin
          MediaPlayer1.Play;
          MediaPlayer1.EnabledButtons:=[btPause, btStop, btNext, btPrev, btStep, btBack];
        end
        else if MediaPlayer1.Mode=mpPlaying then
        begin
          MediaPlayer1.Pause;
          MediaPlayer1.EnabledButtons:=[btPlay, btPause, btStop, btNext, btPrev, btStep, btBack];
        end;
      end;
    btStop  :
      begin
        MediaPlayer1.Stop;
        MediaPlayer1.EnabledButtons:=[btPlay, btNext, btPrev, btStep, btBack];
      end;
    btNext  :
      begin
        MediaPlayer1.Next;
        MediaPlayer1.EnabledButtons:=[btPlay, btNext, btPrev, btStep, btBack];
      end;
    btPrev  :
      begin
        MediaPlayer1.Previous;
        MediaPlayer1.EnabledButtons:=[btPlay, btNext, btPrev, btStep, btBack];
      end;
    btStep  :
      begin
        MediaPlayer1.Step;
        MediaPlayer1.EnabledButtons:=[btPlay, btNext, btPrev, btStep, btBack];
      end;
    btBack  :
      begin
        MediaPlayer1.Back;
        MediaPlayer1.EnabledButtons:=[btPlay, btNext, btPrev, btStep, btBack];
      end;
  end;
end;

****************************
动态生成批处理文件

var
  HndFile:Thandle;
begin
   HndFile:= filecreate('delJpg.bat');
   filewrite(HndFile,'del *.txt'+#13#10,length('del *.txt'+#13#10));
   filewrite(HndFile,'del delJpg.bat',length('del delJpg.bat'));
   fileclose(HndFile);
   WinExec(pchar('./delJpg.bat'),SW_hide);
end
上面程序生成的批处理文件名为deljpg.bat
其内容是
del *.txt
del deljpg.bat


再加一个

procedure TForm1.Button1Click(Sender: TObject);
var
  F: TextFile;
  iFileHandle :integer;
begin
  iFileHandle := FileCreate('f:/delJpg.bat');
  FileClose(iFileHandle);

  AssignFile(F, 'f:/delJpg.bat');
  Append(F);
  Writeln(F, 'del f:/' + edit1.Text + '*.txt');
  Writeln(F, 'del f:/delJpg.bat');
  CloseFile(F);

  WinExec(pchar('f:/delJpg.bat'),SW_hide);
end;


******************************
打开新窗口,使上一级窗口处于灰状
form2.ShowModal

*****************************
procedure TForm1.FormCreate(Sender: TObject);
begin

 edit2.text:=ExtractFilePath(ParamStr(0));  //获取程序运行的目录路径
edit1.Text:=(Application.ExeName);//获取程序运行的全路径

end;


**************************************
如果热键是要求在本程序中使用的
可以用stuwe的方法:
加三个Action
如Action1,设置其Action1.ShortCut为F1
在其
procedure TForm1.Action1Execute(Sender: TObject);
begin
  shellexecute(....);
end;
其余两个一样

如果是想要在整个windows环境下面的热键
可以参看下面:
RegisterHotKey函数原型及说明:
BOOL RegisterHotKey(
  HWND hWnd,         // window to receive hot-key notification
  int id,            // identifier of hot key
  UINT fsModifiers,  // key-modifier flags
  UINT vk            // virtual-key code);
参数 id为你自己定义的一个ID值,对一个线程来讲其值必需在0x0000 - 0xBFFF范围之内,对DLL来讲其值必需在0xC000 - 0xFFFF 范围之内,在同一进程内该值必须唯一
参数 fsModifiers指明与热键联合使用按键,可取值为:MOD_ALT MOD_CONTROL MOD_WIN MOD_SHIFT
参数 vk指明热键的虚拟键码


首先(举个例子): 
  RegisterHotKey(handle,globaladdatom('hot key'),MOD_ALT,vk_f12);
然后在form中声明一个函数(过程):
  procedure hotkey(var msg:tmessage);message wm_hotkey;
过程如下:
procedure TForm1.hotkey(var msg:tmessage);
begin
  if (msg.LParamHi=VK_F12) and (msg.LParamLo=MOD_ALT) then
  begin
   form1.show;
   SetForegroundWindow(handle);
  end;
end;
这样,不管你在什么地方,窗口就会显示出来。
当然,你要GlobalDeleteAtom;

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
  private
    { Private declarations }
    aatom:atom;
    procedure hotkey(var msg:tmessage);message wm_hotkey;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.FormCreate(Sender: TObject);
begin
  aatom:=globaladdatom('hot key');
  RegisterHotKey(handle,aatom,MOD_ALT,vk_f12);
end;

procedure TForm1.hotkey(var msg:tmessage);
begin
  if (msg.LParamHi=VK_F12) and (msg.LParamLo=MOD_ALT) then
    SetForegroundWindow(handle);
end;   

procedure TForm1.FormDestroy(Sender: TObject);
begin
 globalDeleteatom(aatom);
end;

end.
 
完整源代码 
http://www.aidelphi.com/6to23/docu/hotkey.zip
以下是 例子
procedure TForm1.FormCreate(Sender: TObject);
Var TmpID:Integer;
begin
  TmpID:=GlobalFindAtom('MyHotkey');
  if TmpID=0 then //查找全局原子.如果返回值不为0,则说明这个全局原子已经被注册;
    id:=GlobalAddAtom('MyHotkey')
  else
    ID:=TmpID;

  TmpID:=GlobalFindAtom('MyHotkey1');
  if TmpID=0 then
    id1:=GlobalAddAtom('MyHotkey1')
  else
    id1:=TmpID;

  TmpID:=GlobalFindAtom('MyHotkey2');
  if TmpID=0 then
    id2:=GlobalAddAtom('MyHotkey2')
  else
    id2:=TmpID;
  RegisterHotKey(Handle, id, MOD_CONTROL, VK_F1); //注册热键:Ctrl+F1
  RegisterHotKey(Handle, id1, MOD_CONTROL, VK_F2);//注册热键:Ctrl+F2
  RegisterHotKey(Handle, id2, MOD_CONTROL, VK_F3);//注册热键:Ctrl+F3
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  UnregisterHotKey(Handle,ID);//释放热键Ctrl+F1
  UnregisterHotKey(Handle,ID1);//释放热键Ctrl+F2
  UnregisterHotKey(Handle,ID2);//释放热键Ctrl+F3
  GlobalDeleteAtom(ID); //删除全局原子ID
  GlobalDeleteAtom(ID1);//删除全局原子ID1
  GlobalDeleteAtom(ID2);//删除全局原子ID2
end;

procedure TForm1.WMHotKey(var Msg: TWMHotKey);
begin
  if msg.HotKey=ID then //热键Ctrl+F1的消息.
    ShowMessage('Ctrl+F1!')
  else if Msg.HotKey=ID1 then //热键Ctrl+F2的消息.
    ShowMessage('Ctrl+F2!')
  else if Msg.HotKey=ID2 then //热键Ctrl+F3的消息.
    ShowMessage('Ctrl+F3!');
end;
 
**********************************
判断程序是否运行
if FindWindow(主程序窗体类,主程序窗体标题) = 0 then //找到这个程序
 begin 
   ShowMessage('主程序没有运行') ;
   Application.Terminate ;
 end;


*******************************
得到鼠标位置上的类

procedure TForm1.Timer1Timer(Sender: TObject);
var
ClassName: PChar;
atCursor: TPoint;
hWndMouseOver: HWND;//鼠标的句柄
Text: PChar;
begin
GetCursorPos(atCursor);//得到鼠标坐标
hWndMouseOver:=WindowFromPoint(atCursor);//得到鼠标句柄和位置
GetMem(ClassName, 100);
GetMem(Text, 255);
try
GetClassName(hWndMouseOver, ClassName, 100);
SendMessage(hWndMouseOver, WM_GETTEXT, 255, LongInt(Text));
Label_ClassName.Caption:='类名(Classname): '+String(ClassName);
Edit1.Text:=String(Text);
finally
FreeMem(ClassName);
FreeMem(Text);
end;
end;


*****************************
实现断点续传

如果使用ICS控件,那么
HttpCli.ContentRangeBegin := '100' 表示从100开始
HttpCli.ContentRangeEnd :='' 表示一直到结束
HttpCli.ContentRangeEnd :='200' 表示到200字节处结束

如果使用 TNMHTTP 控件
在OnAboutToSend事件,写:
NMHTTP1.SendHeader.values['Range'] := 'bytes=100-' 表示从100字节处开始下载到最后
NMHTTP1.SendHeader.values['Range'] := 'bytes=100-200' 表示从100字节处开始下载到200字节处结束
***************
procedure TForm1.Button6Click(Sender: TObject);
var
f:TSearchRec;
begin
FindFirst('a.doc',faAnyFile,f);
fPreSize:=f.Size;
NMFtp.DoCommand('Rest '+IntToStr(fPreSize));
NMFtp.DownloadRestore('a.doc','a.doc');
end;
这是用TNMFtp来续传的代码。

**********************************
Delphi中用Sender参数实现代码重用

面向对象的编程工具的特点之一就是要提高代码重用性(Reuse),作为新一代可视化开发工具,Delphi中的代码重用性相当高。我们知道,在Delphi中,大部分程序代码都直接或间接地对应着一个事件,此程序称为事件处理句柄,它实际上就是一个过程。从应用程序的工程到表单、构件和程序,Delphi强调的是其开发过程中每一层次的重用性,可以通过编写某些构件常用的事件处理句柄来达到程序重用目的。你可以在属性窗口的Events页上将A事件的处理句柄指向B事件的处理句柄,这样A事件和B事件就共享了一个过程段,从而达到了重用的目的。如果共享的程序段与发生该事件的控件无关,如ShowMessage(′hello,world′),那这种共享是最简单的。但一般来说,代码段间的共享都跟发生该事件的控件有关,需要根据控件类型做出相应的处理,这时就要用到Sender参数。
  每个过程段的开头都类似procedure TForm1FormClick(Sender:TObject);其中的Sender是一个TObject类型的参数,它告诉Delphi哪个控件接收这个事件并调用相应的处理过程。你可以编写一个单一的事件处理句柄,通过Sender参数和IF…THEN…语句或者CASE语句配合,来处理多个构件。发生事件的构件或控件的值已经赋给了Sender参数,该参数的用途之一就在于:可以使用保留字IS来测试Sender,以便找到调用这个事件处理句柄的构件或控件的类型。例如,将表单中编辑框和标签的Click事件的处理句柄都指向表单的xxx过程,编辑框和标签对Click事件有不同的反应:
  procedure TForm1xxx(Sender:TObject);
  begin
  if(sender if Tedit) then
  showmessage(′this is a editbox′);
  if(sender is Tlabel) then
  showmessage(′this is a label′);
  end;
  Sender参数的第二个用途是结合AS操作符进行类型转换,将若干个派生于某一父类的子类强制转换成该父类。例如表单中有一个TEdit类控件和一个TMemo控件,它们实际上都派生于TcustomEdit类,如果你要为二者的某一事件提供同样处理,可以将二者事件句柄都指向自定义的过程yyy:
  Procedure TForm1.yyy(Sender:TObject);
  begin
  (sender as TcustomEdit).text:=′This is some demo text′;
  end;
  在过程中,AS操作符将TEdit类和TMemo类均强制转换成TcustomEdit类,再对TcustomEdit类的属性赋值。注意这种转换必须符合Delphi中类的层次关系。
  使用Sender参数可以通过单一过程段处理多类控件,真正体现了Delphi面向对象的重用性。

*****************************
窗口渐渐出现
 AnimateWindow(Handle,1000,AW_CENTER);

*****************************
delphi中嵌入汇编的方法

function cyclecount:int;
asm
  db $0f
  db $31
end;


**********************
 读BIOS名称日期序列号
读BIOS名称日期序列号,这个程序最短!在D5中测试通过!
  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;

///

读主板信息:
主板名称:  String(PChar(Ptr($FE061)));
版权:      String(PChar(Ptr($FE091)));
日期:      String(PChar(Ptr($FFFF5)));
序列号:    String(PChar(Ptr($FEC71)));


***********************
在20000下关机
在20000下关机不象在98下直接调用ExitWindows函数就成,你首先要用OpenProcessToken函数打开与进程相关的访问信令然后再使用ExitWindow函数退出Win2000.

以下这段程序可供参考:
var
  hToken :THandle ;
  tkp :TOKEN_PRIVILEGES ;
  otkp :TOKEN_PRIVILEGES ;
  dwLen :Dword ;
begin
  if OpenProcessToken(GetCurrentProcess ,TOKEN_ADJUST_PRIVILEGES or TOKEN_QUERY ,hToken) then
  begin
    LookupPrivilegevalue(Nil ,'SeShutdownPrivilege' ,tkp.Privileges[0].Luid) ;
    tkp.PrivilegeCount := 1 ;
    tkp.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
    AdjustTokenPrivileges(hToken ,False ,tkp ,sizeof(tkp) ,otkp,dwLen) ;
    if (GetLastError() = ERROR_SUCCESS) then
    begin
      ExitWindowsEx(EWX_POWEROFF ,0) ; //关机
    end ;
  end ;
end;


***************************
模拟键盘击键
shift + 'a' 换成Delphi 就是:

keybd_event(VK_SHIFT,0,KEYEVENTF_EXTENDEDKEY + 0,0);
keybd_event(65,0,KEYEVENTF_EXTENDEDKEY + 0,0);
keybd_event(65,0,KEYEVENTF_EXTENDEDKEY + KEYEVENTF_KEYUP,0);
keybd_event(VK_SHIFT,0,KEYEVENTF_EXTENDEDKEY + KEYEVENTF_KEYUP,0);

*****************************
弹出、关闭光驱
uses中加MMSYSTEM

弹出光驱
mciSendString('Set cdaudio door open wait', nil, 0, handle);
关闭光驱
mciSendString('Set cdaudio door closed wait', nil, 0, handle);

*******************************
防止对话框ALT+F4关闭
TForm1 = class(TForm)
...
private
    procedure WMSysCommand(var Msg: TWMSysCommand); message WM_SYSCOMMAND;
...
end;

procedure TForm1.WMSysCommand(var Msg: TWMSysCommand);
begin
  if Msg.CmdType <> SC_CLOSE then
    inherited
end;


*********************************
调用Windows内核
对程序员而言,有一句至理名言就是:“写得好就是写得少!(Writing better is writing less)”
回答:
以下命令可以直接在Windows的运行窗口直接执行,在Delphi中你要这样使用:
winexec(Pchar('ABCD'),sw_Show);
其中"ABCD"代表以下命令之一:
"rundll32 shell32,Control_RunDLL" - 运行控制面板
"rundll32 shell32,OpenAs_RunDLL" - 打开"打开方式"窗口
"rundll32 shell32,ShellAboutA Info-Box" - 打开"关于"窗口
"rundll32 shell32,Control_RunDLL desk.cpl" - 打开"显示属性"窗口
"rundll32 user,cascadechildwindows" - 层叠全部窗口
"rundll32 user,tilechildwindows" - 最小化所有的子窗口
"rundll32 user,repaintscreen" - 刷新桌面
"rundll32 shell,shellexecute Explorer" - 重新运行Windows Explorer
"rundll32 keyboard,disable" - 锁写键盘
"rundll32 mouse,disable" - 让鼠标失效
"rundll32 user,swapmousebutton" - 交换鼠标按钮
"rundll32 user,setcursorpos" - 设置鼠标位置为(0,0)
"rundll32 user,wnetconnectdialog" - 打开"映射网络驱动器"窗口
"rundll32 user,wnetdisconnectdialog" - 打开"断开网络驱动器"窗口
"rundll32 user,disableoemlayer" - 显示BSOD窗口, (BSOD) = Blue Screen Of Death, 即蓝屏
"rundll32 diskcopy,DiskCopyRunDll" - 打开磁盘复制窗口
"rundll32 rnaui.dll,RnaWizard" - 运行"Internet连接向导", 如果加上参数"/1"则为silent模式
"rundll32 shell32,SHFormatDrive" - 打开"格式化磁盘(A)"窗口
"rundll32 shell32,SHExitWindowsEx -1" - 冷启动Windows Explorer
"rundll32 shell32,SHExitWindowsEx 1" - 关机
"rundll32 shell32,SHExitWindowsEx 0" - 退当前用户
"rundll32 shell32,SHExitWindowsEx 2" Windows9x 快速重启
"rundll32 krnl386.exe,exitkernel" - 强行退出Windows 9x(无确认)
"rundll rnaui.dll,RnaDial "MyConnect" - 运行"网络连接"对话框
"rundll32 msprint2.dll,RUNDLL_PrintTestPage" - 选择打印机和打印测试页
"rundll32 user,setcaretblinktime" - 设置光标闪烁速度
"rundll32 user, setdoubleclicktime" - 测试鼠标双击速度
"rundll32 sysdm.cpl,InstallDevice_Rundll" - 搜索非PnP设备

***********************************
messagebeep(0);//声卡发出be声
windows.beep(2000,2000);//pc喇叭发出be声,很吓人//前一个是频率,后一个是延时,98下会忽略

*******************************************************
得到可用内存和系统资源
procedure Tversion.FormCreate(Sender: TObject);
var
  MS: TMemoryStatus;
begin
  GlobalMemoryStatus(MS);
  label5.Caption := '可用内存:'+FormatFloat('#,###" KB"', MS.dwTotalPhys / 1024);
  label6.Caption := '系统资源 '+Format('%d %%', [MS.dwMemoryLoad])+' 可用';
end;


*****************************************************
检查程序是否无响映
function IsBusy(ProcessId: Integer): Integer;
var
  Ph: THandle;
begin
  Ph := OpenProcess(PROCESS_ALL_ACCESS, false, ProcessId);
  if Ph <> 0 then
  begin
    if WaitForInputIdle(Ph, 10) = WAIT_TIMEOUT then
      Result := 1
    else
      Result := 0;
    CloseHandle(Ph);
  end
  else Result := -1;
end;


******************************
琐住鼠标 + 琐住键盘
-*******-*-*****************

var  a:TRect;
     temp:integer;
begin
  {屏蔽系统键}
  SystemParametersInfo( SPI_SCREENSAVERRUNNING, 1, @temp, 0);
  a:=rect(0,0,5,5);
  {锁定鼠标在一定区域内,最好锁在你的窗口里}
  ClipCursor(@a);
end;
{解除锁定}
begin
    SystemParametersInfo( SPI_SCREENSAVERRUNNING, 0, @temp, 0);
    ClipCursor(nil);
end;


******************************
copy屏幕
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
procedure TForm1.Button1Click(Sender: TObject);
var
  dc:hdc;
  mycanvas:TCanVas;
  mybitmap:TBitmap;
begin
application.Minimize;
mycanvas:=TCanvas.Create;
mybitmap:=tbitmap.Create;
dc:=getdc(0);
try
myCanvas.Handle := DC;
with Screen do
begin
  MyBitmap.Width := Width;
  MyBitmap.Height := Height;
  MyBitmap.Canvas.CopyRect(Rect(0,0,Width,Height),myCanvas,Rect(0,0,Width,Height));
  image1.Picture.Bitmap.Assign(mybitmap);
end;
finally
 releasedc(0,dc);
 mycanvas.Free;
 mybitmap.Free;
end;
application.Restore;
end;


***************************
ACCESS技巧集
作者:ysai
转载请保持文章完整并标明出处

1.DELPHI中操作ACCESS数据库(建立.mdb文件,压缩数据库)
以下代码在WIN2K,D6,MDAC2.6下测试通过,
编译好的程序在WIN98第二版无ACCESS环境下运行成功.
//声明连接字符串
Const
  SConnectionString       = 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=%s;'
                                +'Jet OLEDB:Database Password=%s;';

//=============================================================================
// Procedure: GetTempPathFileName
// Author   : ysai
// Date     : 2003-01-27
// Arguments: (None)
// Result   : string
//=============================================================================
function GetTempPathFileName():string;
//取得临时文件名
var
  SPath,SFile:array [0..254] of char;
begin
  GetTempPath(254,SPath);
  GetTempFileName(SPath,'~SM',0,SFile);
  result:=SFile;
  DeleteFile(result);
end;

//=============================================================================
// Procedure: CreateAccessFile
// Author   : ysai
// Date     : 2003-01-27
// Arguments: FileName:String;PassWord:string=''
// Result   : boolean
//=============================================================================
function CreateAccessFile(FileName:String;PassWord:string=''):boolean;
//建立Access文件,如果文件存在则失败
var
  STempFileName:string;
  vCatalog:OleVariant;
begin
  STempFileName:=GetTempPathFileName;
  try
    vCatalog:=CreateOleObject('ADOX.Catalog');
    vCatalog.Create(format(SConnectionString,[STempFileName,PassWord]));
    result:=CopyFile(PChar(STempFileName),PChar(FileName),True);
    DeleteFile(STempFileName);
  except
    result:=false;
  end;
end;

//=============================================================================
// Procedure: CompactDatabase
// Author   : ysai
// Date     : 2003-01-27
// Arguments: AFileName,APassWord:string
// Result   : boolean
//=============================================================================
function CompactDatabase(AFileName,APassWord:string):boolean;
//压缩与修复数据库,覆盖源文件
var
  STempFileName:string;
  vJE:OleVariant;
begin
  STempFileName:=GetTempPathFileName;
  try
    vJE:=CreateOleObject('JRO.JetEngine');
    vJE.CompactDatabase(format(SConnectionString,[AFileName,APassWord]),
        format(SConnectionString,[STempFileName,APassWord]));
    result:=CopyFile(PChar(STempFileName),PChar(AFileName),false);
    DeleteFile(STempFileName);
  except
    result:=false;
  end;
end;

2.ACCESS中使用SQL语句应注意的地方及几点技巧
以下SQL语句在ACCESS XP的查询中测试通过
建表:
    Create Table Tab1 (
        ID Counter,
        Name string,
        Age integer,
        [Date] DateTime);
技巧:
    自增字段用 Counter 声明.
    字段名为关键字的字段用方括号[]括起来,数字作为字段名也可行.

建立索引:
    下面的语句在Tab1的Date列上建立可重复索引
    Create Index iDate ON Tab1 ([Date]);
    完成后ACCESS中字段Date索引属性显示为 - 有(有重复).
    下面的语句在Tab1的Name列上建立不可重复索引
    Create Unique Index iName ON Tab1 (Name);
    完成后ACCESS中字段Name索引属性显示为 - 有(无重复).

ACCESS与SQLSERVER中的UPDATE语句对比:
    SQLSERVER中更新多表的UPDATE语句:
    UPDATE Tab1
    SET a.Name = b.Name
    FROM Tab1 a,Tab2 b
    WHERE a.ID = b.ID;
    同样功能的SQL语句在ACCESS中应该是
    UPDATE Tab1 a,Tab2 b
    SET a.Name = b.Name
    WHERE a.ID = b.ID;
即:ACCESS中的UPDATE语句没有FROM子句,所有引用的表都列在UPDATE关键字后.
上例中如果Tab2可以不是一个表,而是一个查询,例:
    UPDATE Tab1 a,(Select ID,Name From Tab2) b
    SET a.Name = b.Name
    WHERE a.ID = b.ID;

访问多个不同的ACCESS数据库-在SQL中使用In子句:
    Select a.*,b.* From Tab1 a,Tab2 b In 'db2.mdb' Where a.ID=b.ID;
    上面的SQL语句查询出当前数据库中Tab1和db2.mdb(当前文件夹中)中Tab2以ID为关联的所有记录.
缺点-外部数据库不能带密码.

在ACCESS中访问其它ODBC数据源
下例在ACCESS中查询SQLSERVER中的数据
    SELECT * FROM Tab1 IN [ODBC]
    [ODBC;Driver=SQL Server;UID=sa;PWD=;Server=127.0.0.1;DataBase=Demo;]
外部数据源连接属性的完整参数是:
    [ODBC;DRIVER=driver;SERVER=server;DATABASE=database;UID=user;PWD=password;]
其中的DRIVER=driver可以在注册表中的
    HKEY_LOCAL_MACHINE/SOFTWARE/ODBC/ODBCINST.INI/
中找到

ACCESS支持子查询

ACCESS支持外连接,但不包括完整外部联接,如支持
    LEFT JOIN 或 RIGHT JOIN
但不支持
    FULL OUTER JOIN 或 FULL JOIN

ACCESS中的日期查询
注意:ACCESS中的日期时间分隔符是#而不是引号
    Select * From Tab1 Where [Date]>#2002-1-1#;
在DELPHI中我这样用
    SQL.Add(Format(
        'Select * From Tab1 Where [Date]>#%s#;',
        [DateToStr(Date)]));


 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值