码迷,mamicode.com
首页 > Windows程序 > 详细

历史上最全的delphi技巧集锦

时间:2015-07-10 10:50:22      阅读:1085      评论:0      收藏:0      [点我收藏+]

标签:

历史上最全的delphi技巧集锦  

 
------------------------------------------------
删除dbgrid中选定数据的方法:
begin
      adotable1.Delete;
      adotable1.first;
若要追加和修改信息:adotable1.Append;adotable1.post;
------------------------------------------------
将数据写入库:
procedure Tclassmanageform.SaveToTable;
begin
    ClassmanageForm.adotable1.edit;
    ClassmanageForm.adotable1.FieldByName(‘班级名‘).asstring:=edit1.text;
    ClassmanageForm.adotable1.FieldByName(‘入学时间‘).asdatetime:=StrToDate(edit9.text);
    ClassmanageForm.adotable1.FieldByName(‘所在院系‘).AsString:=edit3.text;
    ClassmanageForm.adotable1.FieldByName(‘班长‘).asstring:=edit4.text;
    ClassmanageForm.adotable1.fieldbyname(‘班长联系电话‘).asstring:=edit5.text;
    //ClassmanageForm.adotable1.FieldByName(‘班主任‘).asstring:=edit6.text;
    //ClassmanageForm.adotable1.FieldByName(‘班主任联系电话‘).asstring:=edit7.text;
    ClassmanageForm.adotable1.FieldByName(‘操作员‘).asstring:=mainform.username;
    ClassmanageForm.adotable1.FieldByName(‘最后修改时间‘).asdatetime:=date();
    ClassmanageForm.adotable1.FieldByName(‘所学专业‘).asstring:=edit2.text;
    ClassmanageForm.adotable1.FieldByName(‘班级人数‘).asinteger:=StrToInt(edit8.text);
    ClassmanageForm.adotable1.Post;
end;
------------------------------------------------
显示一个提示对话框:
application.MessageBox(‘提示‘,‘您确定要删除该班级吗?‘,mb_iconinformation+mb_yesno);
如要点‘是’的话,可以写为:
if (application.MessageBox(‘提示‘,‘您确定要删除该班级吗?‘,mb_iconinformation+mb_yesno))
 
=IdYes then
……
mb_iconinformation:提示图标 mb_iconwarning:警告图标    
------------------------------------------------
判断一个内容框中的值是否为空,为空时‘确定’按纽不可用:
  if (length(edit1.Text)>1) and (length(edit2.Text)>1) and (length(edit3.Text)>1) and
      (length(edit4.Text)>1) and (length(edit5.Text)>1) and (length(edit8.Text)>1) then
     bitbtn1.Enabled:=true
  else
    bitbtn1.Enabled:=false;
------------------------------------------------
进入一开始就读出数据库的信息并显示到EDIT中(写一个函数):
procedure Tclassmanageform.LoadFromTable;
begin
   ClassmanageForm.edit1.text:=adotable1.FieldByName(‘班级名‘).asstring;
   ClassmanageForm.edit9.text:=DatetoStr(adotable1.FieldByName(‘入学时间‘).asdatetime);
   ClassmanageForm.edit3.text:=adotable1.FieldByName(‘所在院系‘).AsString;
   ClassmanageForm.edit4.text:=adotable1.FieldByName(‘班长‘).asstring;
   ClassmanageForm.edit5.Text:=adotable1.fieldbyname(‘班长联系电话‘).asstring;
   //ClassmanageForm.edit6.text:=adotable1.FieldByName(‘班主任‘).asstring;
   //ClassmanageForm.edit7.Text:=adotable1.FieldByName(‘班主任联系电话‘).asstring;
   ClassmanageForm.edit2.text:=adotable1.FieldByName(‘所学专业‘).asstring;
   ClassmanageForm.edit8.text:=IntToStr(adotable1.FieldByName(‘班级人数‘).asinteger);
end;
------------------------------------------------
如何实现数据库的备份与恢复:
备份:
procedure TBackupFrm.BitBtn2Click(Sender: TObject);
begin
if Edit1.Text= ‘ then
begin
Showmessage(‘无选择要保存的文件名‘);
exit;
end;
try
try
dmData.adoQryTmp.Active:= false;
dmData.adoQryTmp.SQL.Clear;
dmData.adoQryTmp.SQL.Add(‘BACKUP DATABASE [dzyl] TO DISK = ‘‘+edit1.text+‘‘ WITH INIT‘);
dmData.adoQryTmp.ExecSQL;
finally
begin
dmData.adoQryTmp.Active:= false;
Showmessage(‘数据库备份成功!‘);
end;
end;
except
on e:exception do
begin
ShowMessage(‘数据库备份失败!‘);
end;
end;
end;
---------------------------
恢复
procedure TBackupFrm.BitBtn4Click(Sender: TObject);
begin
  if Edit2.Text = ‘ then
  begin
    showmessage(‘未选择要恢复的数据库文件!‘);
    exit;
  end;
  with dmData do
  begin
    try
      adocmmd.CommandText:=‘use master‘;
      adocmmd.Execute;
      adocmmd.CommandText:=‘alter database dzyl set offline with rollback immediate‘;
      adocmmd.Execute;
      adocmmd.CommandText:=‘restore database dzyl from disk= ‘‘+edit2.Text+‘‘ with 
 
recovery ‘;
      adocmmd.Execute;
      adocmmd.CommandText:=‘ alter database dzyl set online with rollback immediate‘;
      adocmmd.Execute;
      showmessage(‘数据库恢复成功!‘);
      application.Terminate;
    except
      on e:exception do
      begin
        showmessage(‘数据库恢复失败!‘+e.Message);
      end;
 
  end;
end;
其中dmData.adoQryTmp连接的是系统MASTER数据库,备份还原之前应该关闭要备份还原的AdoConn数据库
 
连接AdoConn.Connected:=False;
------------------------------------------------
另一方法:
备份如下:
        try
            backupString := ‘BACKUP DATABASE [Paper] TO  DISK = N‘‘+edit1.Text+‘‘ WITH  
 
INIT ,  NOUNLOAD ,  NAME = N‘Paper 备份‘,  NOSKIP ,  STATS = 10,  NOFORMAT‘;
            adoquery1.Close;
            adoquery1.SQL.Clear;
            adoquery1.SQL.Add(backupString);
            ADOQuery1.Prepared;
            adoquery1.ExecSQL;
            application.MessageBox(‘备份成功。‘,‘提示‘,0);
        except
            application.MessageBox(‘备份出错!请重新备份数据。‘,‘出错‘,0);
        end;
---------------------------
还原如下:
            if opendialog1.Execute then
            begin
                try
                    adoquery1.Close();
                    adoquery1.SQL.Clear;
                    adoquery1.SQL.Add(‘use master‘);
                    adoquery1.Prepared;
                    adoquery1.ExecSQL;
                    restorestring := ‘RESTORE DATABASE [Paper] FROM  DISK = 
 
N‘‘+opendialog1.FileName+‘‘ WITH  FILE = 1,  NOUNLOAD ,  STATS = 10,  REPLACE,RECOVERY‘;
                    self.ADOCommand1.CommandText := restoreString;
                    adocommand1.Execute;
                    application.MessageBox(‘还原数据成功‘,‘提示‘,0);
 
                    adoquery1.Close();
                    adoquery1.SQL.Clear;
                    adoquery1.SQL.Add(‘use paper‘);
                    adoquery1.Prepared;
                    adoquery1.ExecSQL;          
                except
                    application.MessageBox(‘还原数据出错!请重新还原,并停止一切的数据操作!
 
‘,‘提示‘,0);
                end;
            end;
------------------------------------------------
判断一个输入框中字符的合法性:
在keypress事件中写入:
  if not(key in [‘0‘..‘9‘,#8,#13]) then
    begin
    key:=#0;
    showmessage(‘请您正确填写电话号码!‘);
    end;
------------------------------------------------
使用combobox时,让拉动菜单不可修改:
将style属性设为csdropdownlist。
------------------------------------------------
如何使得在使用pagecontrol组件时,按快捷键就会跳到相应Tabsheet中去?
首先,把form窗体的keypreview设为true,然后在form的onkeydown事件中写:
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  case key of
          VK_F1agecontrol1.Pages[0].Show;
          VK_F2agecontrol1.Pages[1].show;
          VK_F3agecontrol1.Pages[2].Show;
  end;
end;
------------------------------------------------
给应用程序设置全局快捷键,本程序设置了 2 个快捷键,无论现在的焦点在哪个控件上,按 Ctrl+R 和 
 
Ctrl+Q 都会调用对应的过程。
    
unit Unit1;
interface
uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
  TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
protected
procedure hotykey(var msg: TMessage); message WM_HOTKEY;
  end;
var
Form1: TForm1;
id, id2: Integer;
implementation
{$R *.DFM}
    
procedure TForm1.hotykey(var msg: TMessage);
begin
  if (msg.LParamLo=MOD_CONTROL) and (msg.LParamHi=81) then
     begin
       ShowMessage(’Ctrl + Q ’);
     end;
  if (msg.LParamLo=MOD_CONTROL) and (msg.LParamHi=82) then
     begin
       ShowMessage(’Ctrl + R ’);
     end;
end;
    
procedure TForm1.FormCreate(Sender: TObject);
  begin
    id :=GlobalAddAtom(’hotkey’);
    RegisterHotKey(handle, id, mod_control, 81);
    id2 :=GlobalAddAtom(’hotkey2’);
    RegisterHotKey(handle, id2, mod_control, 82);
  end;
    
procedure TForm1.FormDestroy(Sender: TObject);
  begin
    UnRegisterHotKey(handle,id);
    UnRegisterHotKey(handle,id2);
  end;
------------------------------------------------
怎样实现在使用treeview时,当点击一个分支时,从数据库中读出相应数据:
if xsda_form.TreeView1.Items[1].Selected then
  begin
     xsda_form.Caption:=‘学生档案‘;
     xsda_form.Caption:=xsda_form.Caption+‘(‘+xsda_form.TreeView1.Items[0].Text+‘  
 
‘+xsda_form.TreeView1.Items[xi_shuxue].Text+xsda_form.TreeView1.Items[ji_02].Text+‘级)‘;
     xsda_form.Query1.SQL.Clear;
     xsda_form.Query1.SQL.Add(‘select *‘);
     xsda_form.Query1.SQL.Add(‘from shuxuexi_xsda.db‘);
     xsda_form.Query1.SQL.Add(‘where Rxsj=‘‘+xsda_form.TreeView1.Items[ji_02].Text+‘‘);
     xsda_form.Query1.Active;
     xsda_form.Query1.Open;
  end;
------------------------------------------------
如何在面板上判断所指对象为某控件时,都会统一做出响应:
procedure TMainForm.Button1Click(Sender: TObject);
begin
if Sender = Button1 then     //此处也可以看是否为edit1啊,其他一些控件 
  AboutBox.Caption := ‘About ‘ + Application.Title 
else 
  AboutBox.Caption := ‘; 
AboutBox.ShowModal;
end;
------------------------------------------------
如何把鼠标的移动区域限制在(100,100,200,200)
var rect:TRect;
begin
rect.Left:=100;
rect.Top:=100;
rect.Bottom:=200;
rect.Right:=200;
windows.ClipCursor(@rect);
 
下面恢复鼠标的移动区域
windows.ClipCursor(0);
------------------------------------------------
1、怎么样在delphi中调动其它*.exe文件?
例如:winexec(‘d:\郑洽\Project1.exe‘,sw_show);
 
==============================================================================
 
2、如何让工程运行时主窗体就是最大化的? 
答:设置主窗体的WindowsState属性为wsMaximized就可以了!
wsNormal 窗体以普通状态显示
wsMinimized 窗体以最小化状态显示。
wsMaximized 窗体以最大化状态显示。 
 
==============================================================================
 
3、我想先->闪现窗体->主窗体->登录窗体,工程源文件怎么设置?
答:
⒈开始一个新工程。给表格起名为MainForm,MainForm的单元起名为Main, 工程文 件起名为Test。
⒉在MainForm中插入一个Button部件,将其Caption属性设为“关闭”,为该部件 的onClick事件创建一
 
个过程,并在过程的begin和end之间插入Close语句。
⒊在应用程序添加一个表格,将这个表格起名为MoveForm,MoveForm 的单元起名 为Move。
⒋为便于演示,在MoveForm中插入一个Label部件,设置其Caption 属性为“欢迎 进入本系统”。
5.下一步修改工程的源代码。选择View/Project Source,修改begin和end之间的 语句如下:
程序清单Test.Dpr
program Test
uses
forms,
Main in ‘MAIN.PAS‘{MainForm},
Move in ‘Move.PAS‘{MoveForm}
 
{$R *.RES}
 
begin
MoveForm:=TMoveForm.Create(Application);{Create创建闪现窗口对象}
MoveForm.Show;
MoveForm.Update;
Application.CreateForm(TMainForm,MainForm);
MoveForm.Hide;
MoveForm.Free;{Free从内存中释放对象}
Application.Run;
end.
  第一条语句创建了对象,该对象存在内存中,但还不能看见, 为了让它出现并更 新它的内容,调用
 
对象的Show和Update成员函数:Show和Update。 当闪现窗口使 用完后,用Hide函数将它隐藏起来,然后
 
用Free函数释放它所占据的内存。
6.如果此刻你编译和运行程序,MoveForm窗口一闪而过, 你可能未来得及看 清。为使MoveForm窗口显示
 
几秒种,我们可为MainForm的OnCreate 事件创建一个 处理程序,延迟MoveForm窗口的显现时间。
program TMainForm.FormCreate(sender:Tobject);
var 
currentTime:LongInt;
begin
currentTime:=GetTickCount div 1000;
while ((GetTickCount div 1000)<(currentTime+3) do
{不做任何事);
end;
end.
  GetTickCount函数返回窗口启动后过去的毫秒数,这个值除以1000 转化为秒数。 此时你编译运行程
 
序,就能得到一个延迟3秒多的闪现窗口。
为闪现窗口添加上Image部件,再对字体及窗口进行修饰,我们就能为应用程 序,创建一个精美的封面或
 
在程序启动时显示重要提示。
 
制作登录窗体一个很方便的方法就是主窗体作为主窗体,登录成功Hide掉就行了。
如果登录窗体不可以作为主窗体,那么和闪现窗体一样的方法创建登录窗体,加在Application.Run;之前
 
,MoveForm.Free;之后,
用showmodal显示登录窗体
 
==============================================================================
 
4、button上面的文字怎么样换行?
答:
button控件不行
bitbtn控件可以。
bitbtn1.caption:=‘aaaa‘#13‘bbbbb‘
 
==============================================================================
 
5、怎么样判别焦点是否在某个控件上?
答:
if Tobject.focused then
//焦点在某某控件上
else
 
==============================================================================
 
6、怎么样在程序中使一个节点的子节点展开及收闭?
答:
treeview1.selected.Expanded; //判断节点的子节点是否展开True展开,否则闭拢
treeview1.selected.Expand(True);//子节点展开
treeview1.selected.collapse(True)://子节点闭拢 
 
树节点全部展开:
procedure TForm1.Button1Click(Sender: TObject);
var node:TTreeNode;
begin
if treeview1.Items[0]<>nil then
begin
node:=treeview1.Items[0];
node.Expand(true);
while node.getNextSibling<>nil do
begin
node:=node.getNextSibling;
node.Expand(true);
end;
end;
end;
 
 
树节点全部收缩:
procedure TForm1.Button2Click(Sender: TObject);
var node:TTreeNode;
begin
if treeview1.Items[0]<>nil then
begin
node:=treeview1.Items[0];
node.Collapse(true);
while node.getNextSibling<>nil do
begin
node:=node.getNextSibling;
node.Collapse(true);
end;
end;
end;
 
==============================================================================
 
7、如何用delphi编程实现给access数据库加密码?
答:1,新建Project。
  2,在FORM中放入ADOConnection控件。
  3,双击ADOConnection控件,然后点击Build...按钮,在“提供者”页中选择“Microsoft Jet 4.0 
 
OLE DB   Provider”,然后点击“下一步”按钮,在“连接”页中选择要连接的Access数据库的路径
 
和数据库的文件名,这时如果点“测试连接”按钮时,出现“初始化提供者时发生错误,测试连接失败,
 
密码无效”的错误提示。
  4,这时点“所有”页,然后双击“Jet OLEDBatabase Password”,出现对话框,添入密码后,选
 
择“连接”页中的“测试连接”按钮,出现“测试连接成功”的对话框。把ADOConnection控件的
 
LoginPromtp设为false.
  5,设置连接完成。
 
==============================================================================
 
8、如何判断Treeview中我选中的节点是否有子节点?如果没有给出提示啊?
答:
if Treeview.Selected.HasChildren then
//有
else
//无 
 
var
Node :TTreeNode;
begin
Node :=TreeView1.Selected;
if Node.HasChildren then
....
对复杂的程序最好用Node过渡
 
==============================================================================
 
9、能否解释一下try...except...end及try...finally...end;?
1.(1)是用于扑捉异常,(2)是用于保证代码执行的完整性
2.(1)中finally处的代码不管什么情况都会被执行,(2)中except处的代码仅在发生异常时才会执行
3.try finally之间的代码虽可保证finally 和 end之间的程序能执行,但不能保证程序不崩溃,
而try except就不会使程序崩溃 
 
==============================================================================
 
10、怎么样在主程序控制器中加入音乐?
在implementation下加入 mmsystem單元(windows多媒體函數動態聯結庫)。然後在的onShow,onCreate
 
事件中編寫代碼:sndplaysound(‘sound.wav‘,snd_async)
 
==============================================================================
 
11、我在form1上有四个edit,输完后我想用下上箭头键进行上移下移?怎么办?
答:
procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=vk_down then perform(WM_NEXTDLGCTL,0,0) else
if key=vk_up then perform(WM_NEXTDLGCTL,1,0);
end;
 
==============================================================================
 
12、如何用delphi5实现读文本文件指定的一行,并得到文本文件的总行数?谢谢!
答:
Delphi读文件文件一般使用Readln过程,如要读第3行可以这样: 
var 
i : Integer; 
F: TextFile; 
S: string; 
begin 
if OpenDialog1.Execute then { Display Open dialog box } 
begin 
AssignFile(F, OpenDialog1.FileName); { File selected in dialog } 
Reset(F); 
For i = 1 To 3 Do 
Readln(F, S); 
Edit1.Text := S; { Put string in a TEdit control } 
CloseFile(F); 
.
end; 
要统计总行数,只能从头逐行读,直到文件尾(Eof函数为True),每读一行计数器加1。 
不过由于文本文件的每行长度不相等,它不能象数据库文件那样想读那行就读哪行,只能顺序读。 
上面的方法容易理解,也容易实现。如果希望提高速度,编程上要麻烦一些,可以以二进制方式打开文件
 
,将所有内容读入一个内存变量,然后使用Pos函数查找其中的回车(#13)个数,这样可以快速地统计总
 
行数并能快速地找到指定行。
 
==============================================================================
 
13、制作主窗口显示前的版权窗口 
答:
在工程文件中选File->New Form新建一个窗口,设计好窗口的外观。给窗口起名为AboutBox,选Project-
 
>Options,将新建的窗口从自动建立中去掉。 选View->Project Source,打开工程文件的源文件,在下
 
面加入红色的句子。
Uses AboutBox
Var
lTime :TDateTime;
Begin
Application.Initialize();
AboutBox=TAboutBox.Create(AboutBox);
AboutBox.Show;
AboutBox.Update;
lTime=GetTickCount;
Application.CreateForm(TMainForm,MainForm);
while((GetTickCount-lTime) / 1000 <3) do;
AboutBox.Hide;
AboutBox.Free;
Application.Run;
end; 
 
==============================================================================
 
14、Delphi中RichEdit的奥妙
  一、如何得知当前行号   
  用RichEdit(或者memo)控件制作文本编辑器时,通过访问lines?count属性可以得到总行数,但是
 
若想知道光标当前所在行的行号就麻烦了,因为delphi没有提供这个属性。要实现这个编辑器必备功能,
 
就须调用em_ LineFromChar。
 
  请试试下面的程序。
  先在窗口中布置一个RichEdit或者memo(命名为editor),以及一个button。在button的onclick事
 
件中写入下列代码。
   var
   CurrentLine:Integer;
   begin
     CurrentLine:=Editor.Perform(em_ LineFromChar,SFFFF,0);   
     Application.MessageBox(PChar(′当前行号是′+IntToStr(CurrentLine)),′消息′,mb_ 
 
iconinformation);   
   end;
  需要注意的是,第一行的行号为零。
 
  二、如何撤消操作(undo)
  对于memo来说,实现undo是不需编程的,只要让popupmenu属性为空,运行时就能用鼠标右键激活一
 
个常用操作菜单,其中包括撤消、剪切、复制、粘贴、删除和全选六项。   但可惜的是,这一招对于
 
功能强大的RichEdit控件居然行不通,害得我们还要自己设计一个popupmemu。当你用CutToClipBoard等
 
语句轻松而顺利地完成了“剪切”等功能,接着便会无奈地发现,竟找不到undo或cancel之类的语句来执
 
行“撤消”。   这时你需要这样处理: 
    RichEdit1?Perform(EM_UNDO,0,0);
  另外还应检查是否允许撤消,从而开启或关闭弹出菜单中的“撤消”项:
    Undo1?Enabled:=RichEdit?
    Perform(EM_CANUNDO,0,0)<>0;   
以上程序在Delphi3中调试通过。   
 
 
==============================================================================
 
15、在主窗口中打开另一个独立的窗口,而这个被打开的窗口固定显示在..?
答:
procedure TForm2.FormCreate(Sender: TObject);
begin
form2.Hide;
self.Parent:=form1.Panel1;
end;
 
==============================================================================
 
16、SaveDialog1确认文件存不存在的办法?
答:
procedure TForm1.SaveDialog1CanClose(Sender: TObject; 
var CanClose: Boolean); 
begin 
if FileExists(SaveDialog1.FileName) then //如果文件已经存在 
if MessageDlg(‘文件已经存在,保存吗?‘, mtConfirmation, [mbYes, mbNo], 0) <> mrYes then 
Button2.Click  //如果选择了覆盖,则退出,否则,重新让用户选择文件 
end; 
 
==============================================================================
 
17、正确关闭一个MDI子窗口?
答:
Delphi中MDI子窗口的关闭方式默认为缩小而不是关闭,所以当你单击子窗口右上角的关闭按钮时会发觉该子窗口只是最小化,而不是你预期的那样被关闭。解决办法是在子窗口的OnClose事件处理过程中加入如下代码,示例:
 
procedure ChildForm.OnClose(Sender: TObject; var Action: TCloseAction);
begin
Action := caFree;
end; 
 
  Delphi为一个Form的关闭行为指定了四种方式,分别是:
 
caNone 禁止Form被关闭 
caHide Form不被关闭,但是被隐藏。被隐藏的Form仍然可以被程序访问。 
caFree Form被关闭,并且释放其占用的资源。 
caMinimize Form被最小化而不是被关闭,这是MDI子窗口的默认关闭行为。 
 
 
==============================================================================
 
18、怎样记MDI子窗口不在母体运行时就被打开?
答:
在project下的options中forms里面除了form1外,其余的移到右边的框里,然后在调用显示的按钮下编写语句,以form2调用为例:
form2:=Tform2.create(self);
form2.show;
 
==============================================================================
 
19、限制FORM的大小
答:
在FORM私有声明部分加上如下一行: 
 
procedure WMGetMinMaxInfo( var Message:TWMGetMinMaxInfo message WM_GETMINMAXINFO; 
在声明部分加上如下几行: 
procedure TForm1.WMGetMinMaxInfo( var Message :TWMGetMinMaxInfo  
begin 
with Message.MinMaxInfo^ do
begin
ptMaxSize.X := 200; {最大化时宽度}
ptMaxSize.Y := 200; {最大化时高度}
ptMaxPosition.X := 99; {最大化时左上角横坐标}
ptMaxPosition.Y := 99; {最大化时左上角纵坐标}
end;
Message.Result := 0; {告诉Windows你改变了 minmaxinfo}
inherited;
end; 
 
==============================================================================
 
20、随机数生成法
答:
Randomize;
rn:=inttostr(random(9999));
rn1:=inttostr(random(9999));
.....
 
==============================================================================
 
21、怎样把程序隐藏起来,在WINDOWS界面上没有显示??
答:
在application.run之前加入application.showmain:=false! 
 
==============================================================================
 
22、怎样将一个form1.free的form1窗体重新显示?
答:
form2:=TForm2.Create(application);
form2.Show;
 
如果你要创建的Form2窗体能嵌入一个Panel中,指定Parent:
form2:=TForm2.Create(application);
form2.Parent:=panel1;
form2.Show;
 
==============================================================================
 
23、我想在bitbtn上设快捷按钮Esc,怎么办?
答:
procedure TForm1.BitBtn1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if key=27 then
application.Terminate;
end; 
 
设它的cancel属性为true就行了~~
 
==============================================================================
 
24、什么叫做托盘区?
答:
托盘区就是在windows的状态栏下方显示时钟、输入法状态的地方,
 
要把你的程序显示在托盘区:
下面是一个托盘类,只要把下面粘贴到文本文件中,改成TrayIcon.pas,使用时uses TrayIcon就可以了。
 
先声明一个全局变量:
var tray:TTrayNotifyIcon;
 
然后在窗体的OnCreate事件中:
tray:=TTrayNotifyIcon.Create(self);//将窗体创建为托盘
tray.Icon:=application.Icon;//定义托盘的显示图标
tray.IconVisible:=true;//托盘可见
tray.PopupMenu:=popmenu;//给托盘定义一个右击时的弹出菜单
tray.OnDblClick:=trayDblClick;//给托盘定义一个双击事件(当然要自己写了,不过多数情况只有一行,就是Form1.show);
 
 
unit TrayIcon;
 
interface
 
uses Windows, SysUtils, Messages, ShellAPI, Classes, Graphics, Forms, Menus,
StdCtrls, ExtCtrls;
 
type
ENotifyIconError = class(Exception);
 
TTrayNotifyIcon = class(TComponent)
private
FDefaultIcon: THandle;
FIcon: TIcon;
FHideTask: Boolean;
FHint: string;
FIconVisible: Boolean;
FPopupMenu: TPopupMenu;
FonClick: TNotifyEvent;
FOnDblClick: TNotifyEvent;
FNoShowClick: Boolean;
FTimer: TTimer;
Tnd: TNotifyIconData;
procedure SetIcon(Value: TIcon);
procedure SetHideTask(Value: Boolean);
procedure SetHint(Value: string);
procedure SetIconVisible(Value: Boolean);
procedure SetPopupMenu(Value: TPopupMenu);
procedure SendTrayMessage(Msg: DWORD; Flags: UINT);
function ActiveIconHandle: THandle;
procedure OnButtonTimer(Sender: TObject);
protected
procedure Loaded; override;
procedure LoadDefaultIcon; virtual;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Icon: TIcon read FIcon write SetIcon;
property HideTask: Boolean read FHideTask write SetHideTask default False;
property Hint: String read FHint write SetHint;
property IconVisible: Boolean read FIconVisible write SetIconVisible default False;
property PopupMenu: TPopupMenu read FPopupMenu write SetPopupMenu;
property onClick: TNotifyEvent read FonClick write FonClick;
property OnDblClick: TNotifyEvent read FOnDblClick write FOnDblClick;
end;
 
implementation
 
{ TIconManager }
{ This class creates a hidden window which handles and routes }
{ tray icon messages }
type
TIconManager = class
private
FHWindow: HWnd;
procedure TrayWndProc(var Message: TMessage);
public
constructor Create;
destructor Destroy; override;
property HWindow: HWnd read FHWindow write FHWindow;
end;
 
var
IconMgr: TIconManager;
DDGM_TRAYICON: Cardinal;
 
constructor TIconManager.Create;
begin
FHWindow := AllocateHWnd(TrayWndProc);
end;
 
destructor TIconManager.Destroy;
begin
if FHWindow <> 0 then DeallocateHWnd(FHWindow);
inherited Destroy;
end;
 
procedure TIconManager.TrayWndProc(var Message: TMessage);
{ This allows us to handle all tray callback messages }
{ from within the context of the component. }
var
Pt: TPoint;
TheIcon: TTrayNotifyIcon;
begin
with Message do
begin
{ if it’s the tray callback message }
if (Msg = DDGM_TRAYICON) then
begin
TheIcon := TTrayNotifyIcon(WParam);
case lParam of
{ enable timer on first mouse down. }
{ onClick will be fired by OnTimer method, provided }
{ double click has not occurred. }
WM_LBUTTONDOWN: TheIcon.FTimer.Enabled := True;
{ Set no click flag on double click. This will supress }
{ the single click. }
WM_LBUTTONDBLCLK:
begin
TheIcon.FNoShowClick := True;
if Assigned(TheIcon.FOnDblClick) then TheIcon.FOnDblClick(Self);
end;
WM_RBUTTONDOWN:
begin
if Assigned(TheIcon.FPopupMenu) then
begin
{ Call to SetForegroundWindow is required by API }
SetForegroundWindow(IconMgr.HWindow);
{ Popup local menu at the cursor position. }
GetCursorPos(Pt);
TheIcon.FPopupMenu.Popup(Pt.X, Pt.Y);
{ Message post required by API to force task switch }
PostMessage(IconMgr.HWindow, WM_USER, 0, 0);
end;
end;
end;
end
else
{ If it isn’t a tray callback message, then call DefWindowProc }
Result := DefWindowProc(FHWindow, Msg, wParam, lParam);
end;
end;
 
{ TTrayNotifyIcon }
 
constructor TTrayNotifyIcon.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIcon := TIcon.Create;
FTimer := TTimer.Create(Self);
with FTimer do
begin
Enabled := False;
Interval := GetDoubleClickTime;
OnTimer := OnButtonTimer;
end;
{ Keep default windows icon handy... }
LoadDefaultIcon;
end;
 
destructor TTrayNotifyIcon.Destroy;
begin
if FIconVisible then SetIconVisible(False); // destroy icon
FIcon.Free; // free stuff
FTimer.Free;
inherited Destroy;
end;
 
function TTrayNotifyIcon.ActiveIconHandle: THandle;
{ Returns handle of active icon }
begin
{ If no icon is loaded, then return default icon }
if (FIcon.Handle <> 0) then
Result := FIcon.Handle
else
Result := FDefaultIcon;
end;
 
procedure TTrayNotifyIcon.LoadDefaultIcon;
{ Loads default window icon to keep it handy. }
{ This will allow the component to use the windows logo }
{ icon as the default when no icon is selected in the }
{ Icon property. }
begin
FDefaultIcon := LoadIcon(0, IDI_WINLOGO);
end;
 
procedure TTrayNotifyIcon.Loaded;
{ Called after component is loaded from stream }
begin
inherited Loaded;
{ if icon is supposed to be visible, create it. }
if FIconVisible then
SendTrayMessage(NIM_ADD, NIF_MESSAGE or NIF_ICON or NIF_TIP);
end;
 
procedure TTrayNotifyIcon.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = PopupMenu) then
PopupMenu := nil;
end;
 
procedure TTrayNotifyIcon.OnButtonTimer(Sender: TObject);
{ Timer used to keep track of time between two clicks of a }
{ double click. This delays the first click long enough to }
{ ensure that a double click hasn’t occurred. The whole }
{ point of these gymnastics is to allow the component to }
{ receive onClicks and OnDblClicks independently. }
begin
{ Disable timer because we only want it to fire once. }
FTimer.Enabled := False;
{ if double click has not occurred, then fire single click. }
if (not FNoShowClick) and Assigned(FonClick) then
FonClick(Self);
FNoShowClick := False; // reset flag
end;
 
procedure TTrayNotifyIcon.SendTrayMessage(Msg: DWORD; Flags: UINT);
{ This method wraps up the call to the API’s Shell_NotifyIcon }
begin
{ Fill up record with appropriate values }
with Tnd do
begin
cbSize := SizeOf(Tnd);
StrPLCopy(szTip, PChar(FHint), SizeOf(szTip));
uFlags := Flags;
uID := UINT(Self);
Wnd := IconMgr.HWindow;
uCallbackMessage := DDGM_TRAYICON;
hIcon := ActiveIconHandle;
end;
Shell_NotifyIcon(Msg, @Tnd);
end;
 
procedure TTrayNotifyIcon.SetHideTask(Value: Boolean);
{ Write method for HideTask property }
const
{ Flags to show application normally or hide it }
ShowArray: array[Boolean] of integer = (sw_ShowNormal, sw_Hide);
begin
if FHideTask <> Value then
begin
FHideTask := Value;
{ Don’t do anything in design mode }
if not (csDesigning in ComponentState) then
ShowWindow(Application.Handle, ShowArray[FHideTask]);
end;
end;
 
procedure TTrayNotifyIcon.SetHint(Value: string);
{ Set method for Hint property }
begin
if FHint <> Value then
begin
FHint := Value;
if FIconVisible then
{ Change hint on icon on tray notification area }
SendTrayMessage(NIM_MODIFY, NIF_TIP);
end;
end;
 
procedure TTrayNotifyIcon.SetIcon(Value: TIcon);
{ Write method for Icon property. }
begin
FIcon.Assign(Value); // set new icon
{ Change icon on notification tray }
if FIconVisible then SendTrayMessage(NIM_MODIFY, NIF_ICON);
end;
 
procedure TTrayNotifyIcon.SetIconVisible(Value: Boolean);
{ Write method for IconVisible property }
const
{ Flags to add or delete a tray notification icon }
MsgArray: array[Boolean] of DWORD = (NIM_DELETE, NIM_ADD);
begin
if FIconVisible <> Value then
begin
FIconVisible := Value;
{ Set icon as appropriate }
SendTrayMessage(MsgArray[Value], NIF_MESSAGE or NIF_ICON or NIF_TIP);
end;
end;
 
procedure TTrayNotifyIcon.SetPopupMenu(Value: TPopupMenu);
{ Write method for PopupMenu property }
begin
FPopupMenu := Value;
if Value <> nil then Value.FreeNotification(Self);
end;
 
const
{ String to identify registered window message }
TrayMsgStr = ’DDG.TrayNotifyIconMsg’;
 
initialization
{ Get a unique windows message ID for tray callback }
DDGM_TRAYICON := RegisterWindowMessage(TrayMsgStr);
IconMgr := TIconManager.Create;
finalization
IconMgr.Free;
end.
 
==============================================================================
 
25、关于窗体释放的问题(formX.free)?
答:
这个我知道,模式窗口用:form2 := TForm2.Create(Application);
try
if form2.showModal = mrOK then
{do Something}
finally
form2.free;
form2 := nil;
end; 非模式窗口用:if not Assigned(form2) then
form2 := Tfrom2.Create(Application);
form2.show;
 
//然后在form2的Close事件中加入以下句
Action := caFree;
 
//在from2的Destory事件中加入以下句
form2 := nil; 搞定!!!
 
==============================================================================
 
26、关于MDI窗体的问题?
答:
我不知道是如何实现,但我知道一个方法可以实现同样的功能,在打开子窗体前加一句
button1.SendToBack; 
 
==============================================================================
 
27、小数点‘.‘的键号是什么?回车是#13,‘.‘是什么?
答:
你可以用此得出所有键的值procedure TForm1.Edit1KeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
label1.caption:=IntToStr(key);
end; 
 
=============================================================================
listbox从文件中读取列表的操作
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技巧集锦

标签:

原文地址:http://www.cnblogs.com/vov5601/p/4634873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!