分享

Delphi小技巧杂记

 火星家园 2010-12-16
  Delphi小技巧杂记 收藏
//获取任务栏尺寸
procedure TForm1.Button1Click(Sender: TObject);
var
TaskList: HWnd;
Bordered: TRect;
begin
TaskList := FindWindow(’Shell_TrayWnd’, nil);
GetWindowRect(TaskList, Bordered);
Label1.Caption := ’Left: ’ + IntToStr(Bordered.Left);
Label2.Caption := ’Right: ’ + IntToStr(Bordered.Right);
Label3.Caption := ’Top: ’ + IntToStr(Bordered.Top);
Label4.Caption := ’Bottom: ’ + IntToStr(Bordered.Bottom);
end;
 
 
//修改指定路径下的文件只读属性
function PathSetAttr(sFilePath: string): Boolean;
var
SearchRec: TSearchRec;
begin
Result := False;
if Copy(sFilePath, Length(sFilePath) - 1, Length(sFilePath)) <> ’\’ then
   sFilePath := sFilePath + ’\’;
if DirectoryExists(sFilePath) then
begin
   if FindFirst(sFilePath+’*.*’, faAnyFile, SearchRec) = 0 then
   begin
     FileSetAttr(SearchRec.Name, 32);
     while FindNext(SearchRec) = 0 do
       FileSetAttr(SearchRec.Name, 32);
   end;
   Result := True;
end;
end;
 
 
//为控件加边框
procedure WMNCPaint(var Msg: TWMNCPaint); message WM_NCPAINT;
 
procedure TForm1.WMNCPaint(var Msg: TWMNCPaint);
var
dc: hDC;
Pen: hPen;
OldPen: hPen;
OldBrush: hBrush;
begin
inherited;
dc := GetWindowDC(Handle);
msg.Result := 1;
Pen := CreatePen(PS_SOLID, 1, RGB(255, 0, 0));
OldPen := SelectObject(dc, Pen);
OldBrush := SelectObject(dc, GetStockObject(NULL_BRUSH));
Rectangle(dc, 0, 0, Self.Width, Self.Height);
SelectObject(dc, OldBrush);
SelectObject(dc, OldPen);
DeleteObject(Pen);
ReleaseDC(Handle, Canvas.Handle);
end;
 
 
//制作透明窗体
procedure CreateParams(var Params: TCreateParams); override;  //重载 CreateParams 过程的实现
 
procedure TForm1.CreateParams(var Params: TCreateParams);
begin
//先继承原来的 CreateParams 过程
inherited;
//然后修改 Param.ExStyle 的值,使窗体具有透明效果
Params.ExStyle := Params.ExStyle or WS_EX_TRANSPARENT;
end;
 
procedure TForm1.FormCreate(Sender: TObject);
begin
inherited;
//将画布的笔刷样式改成 bsClear 以及时清除窗体原来的内容,这样窗体就有透明效果
Canvas.Brush.Style := bsClear;
end;
 
 
//Memo 组件的光标定位
procedure TForm1.Memo1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
Lpos, Cpos, Linelength: integer;
begin
Lpos := SendMessage(Memo1.Handle, EM_LineFromChar, Memo1.SelStart, 0);
Cpos := SendMessage(Memo1.Handle, EM_LineIndex, Lpos, 0);
LineLength := SendMessage(Memo1.Handle, EM_LineLength, Cpos, 0);
Cpos := Memo1.SelStart - Cpos;
Label1.Caption := IntToStr(Lpos);
Label2.Caption := IntToStr(Cpos);
Label3.Caption := IntToStr(LineLength);
end;
 
//点击客户区也能拖动窗口
procedure WmNCHitTest(var Msg: TWMNCHitTest); message WM_NCHitTest;
 
procedure TForm1.WmNCHitTest(var Msg: TWMNCHitTest);
begin
DefaultHandler(Msg);
if Msg.Result = HTClient then
   Msg.Result := HTCaption;
end;
 
 
//自定义Memo控件的边界
procedure TForm1.Button1Click(Sender: TObject);
var
Rect: TRect;
begin
SendMessage(Memo1.Handle, EM_GETRECT, 0, LongInt(@Rect));
Rect.Left := 20;
Rect.Top := 20;
Rect.Right := Rect.Right - 19;
Rect.Bottom := Rect.Bottom - 19;
SendMessage(Memo1.Handle, EM_SETRECT, 0, LongInt(@Rect));
Memo1.Refresh;
end;
 
 
//在系统菜单上添加自定义菜单项
procedure WMSysCommand(var Msg: TWMSysCommand); message WM_SYSCOMMAND;
 
const
idMyFunc = $f200;
 
procedure TForm1.FormCreate(Sender: TObject);
begin
AppendMenu(GetSystemMenu(Handle, False), MF_STRING, idMyFunc, ’我的系统菜单项’);
end;
 
procedure TForm1.WMSysCommand(var Msg: TWMSysCommand);
begin
inherited;
if Msg.CmdType and $FFF0 = idMyFunc then
   ShowMessage(’我的系统菜单项’);
end;
 
 
 
 
COOLBAR内嵌TOOLBAR,但是TOOLBAR的按钮偏上的解决办法:把COOLBAR的COOLBAND的BORDERSTYLE设为SINGLE。
另外,如果想把主菜单弄到TOOLBAR里面,只要把TOOLBAR的MENU设为主菜单名,并把主菜单的AUTOMERGE设为TRUE即可。
------------------------------------
 
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./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键
 
 
1、判断机器是否网络状态
答:
uses WinInet;
procedure TForm1.Button1Click(Sender: TObject);
function GetOnlineStatus : Boolean;
var ConTypes : Integer;
begin
ConTypes := INTERNET_CONNECTION_MODEM + INTERNET_CONNECTION_LAN + INTERNET_CONNECTION_PROXY;
if (InternetGetConnectedState(@ConTypes, 0) = False)
then Result := False
else Result := True;
end;
begin
if not GetOnlineStatus then ShowMessage(’Not Connected’);
end;
 
=========================================
 
2、[DELPHI]窗体渐渐出现
答:
AnimateWindow(Handle,1000,AW_CENTER);
//在窗体创建事件中
 
=========================================
 
3、如何取得一台机器的CPU占用率 ?
答:
使用下面的方法
interface
 
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
 
const
SystemBasicInformation = 0;
SystemPerformanceInformation = 2;
SystemTimeInformation = 3;
 
type
TPDWord = ^DWORD;
 
TSystem_Basic_Information = packed record
dwUnknown1: DWORD;
uKeMaximumIncrement: ULONG;
uPageSize: ULONG;
uMmNumberOfPhysicalPages: ULONG;
uMmLowestPhysicalPage: ULONG;
uMmHighestPhysicalPage: ULONG;
uAllocationGranularity: ULONG;
pLowestUserAddress: Pointer;
pMmHighestUserAddress: Pointer;
uKeActiveProcessors: ULONG;
bKeNumberProcessors: byte;
bUnknown2: byte;
wUnknown3: word;
end;
 
type
TSystem_Performance_Information = packed record
liIdleTime: LARGE_INTEGER; {LARGE_INTEGER}
dwSpare: array[0..75] of DWORD;
end;
 
type
TSystem_Time_Information = packed record
liKeBootTime: LARGE_INTEGER;
liKeSystemTime: LARGE_INTEGER;
liExpTimeZoneBias: LARGE_INTEGER;
uCurrentTimeZoneId: ULONG;
dwReserved: DWORD;
end;
 
var
NtQuerySystemInformation: function(infoClass: DWORD;
buffer: Pointer;
bufSize: DWORD;
returnSize: TPDword): DWORD; stdcall = nil;
 
 
liOldIdleTime: LARGE_INTEGER = ();
liOldSystemTime: LARGE_INTEGER = ();
SysBaseInfo: TSystem_Basic_Information;
SysPerfInfo: TSystem_Performance_Information;
SysTimeInfo: TSystem_Time_Information;
status: Longint; {long}
dbSystemTime: Double;
dbIdleTime: Double;
function GetCPUUsage:Double;
implementation
function Li2Double(x: LARGE_INTEGER): Double;
begin
Result := x.HighPart * 4.294967296E9 + x.LowPart
end;
 
function GetCPUUsage:Double;
var
bLoopAborted : boolean;
begin
if @NtQuerySystemInformation = nil then
NtQuerySystemInformation := GetProcAddress(GetModuleHandle(‘ntdll.dll‘),
‘NtQuerySystemInformation‘);
// get number of processors in the system
status := NtQuerySystemInformation(SystemBasicInformation, @SysBaseInfo, SizeOf(SysBaseInfo), nil);
if status <> 0 then Exit;
// Show some information
{with SysBaseInfo do
begin
ShowMessage(
Format(‘uKeMaximumIncrement: %d‘#13‘uPageSize: %d‘#13+
‘uMmNumberOfPhysicalPages: %d‘+#13+‘uMmLowestPhysicalPage: %d‘+#13+
‘uMmHighestPhysicalPage: %d‘+#13+‘uAllocationGranularity: %d‘#13+
‘uKeActiveProcessors: %d‘#13‘bKeNumberProcessors: %d‘,
[uKeMaximumIncrement, uPageSize, uMmNumberOfPhysicalPages,
uMmLowestPhysicalPage, uMmHighestPhysicalPage, uAllocationGranularity,
uKeActiveProcessors, bKeNumberProcessors]));
end;
}
bLoopAborted := False;
while not bLoopAborted do
begin
// get new system time
status := NtQuerySystemInformation(SystemTimeInformation, @SysTimeInfo, SizeOf(SysTimeInfo), 0);
if status <> 0 then Exit;
// get new CPU‘s idle time
status := NtQuerySystemInformation(SystemPerformanceInformation, @SysPerfInfo, SizeOf(SysPerfInfo), nil);
if status <> 0 then Exit;
// if it‘s a first call - skip it
if (liOldIdleTime.QuadPart <> 0) then
begin
// Currentvalue = Newvalue - Oldvalue
dbIdleTime := Li2Double(SysPerfInfo.liIdleTime) - Li2Double(liOldIdleTime);
dbSystemTime := Li2Double(SysTimeInfo.liKeSystemTime) - Li2Double(liOldSystemTime);
// CurrentCpuIdle = IdleTime / SystemTime
dbIdleTime := dbIdleTime / dbSystemTime;
// CurrentCpuUsage% = 100 - (CurrentCpuIdle * 100) / NumberOfProcessors
dbIdleTime := 100.0 - dbIdleTime * 100.0 / SysBaseInfo.bKeNumberProcessors + 0.5;
// Show Percentage
//Form1.Label1.Caption := FormatFloat(‘CPU Usage: 0.0 %‘,dbIdleTime);
//Application.ProcessMessages;
// Abort if user pressed ESC or Application is terminated
Result:=dbIdleTime;
bLoopAborted:=True;
//bLoopAborted := (GetKeyState(VK_ESCAPE) and 128 = 128) or Application.Terminated;
end;
// store new CPU‘s idle and
 
 
=========================================
 
4、动态生成控件?
答:
var
TeSpeedButtonX:TTeSpeedButton;
begin
TeSpeedButtonX:=TTeSpeedButton.Create(nil);
TeSpeedButtonX.Caption:=’标题’;
TeSpeedButtonX.Name:=’按钮’+inttostr(X);
TeSpeedButtonX.Parent:=Tetoolbar2;
X:=X+1;
end;
 
=========================================
 
5、我动态创建了多个button,使用时,我怎么判断出用户点击的是哪个button呢?button的各项属性都边成最后创建的那个button的了,怎么办哦?
答1:
教你一招,先设置每个button的tag属性.然后在onclick事件中用(sender as button).tag来判断,相信我,没错的!  
 
答2:
如果你生成的控件不是很多的话,最简单的方法就是,假如你生成控件的父控件是FORM1,利用循环判断控件是否等于FORM1.ACTIVECONTROL,我就是这么用的。ACTIVECONTROL就是记录当前被点击的控件,你也可以直接用它,不过直接只能用到CONTROL的一般属性和方法,循环判断的话就可以用到你生成控件的相关属性。  
 
=========================================
 
6、窗体释放问题
答:
在Form2.OnClose事件中
Action:=caFree;
 
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 OLEDB:Database 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;
 
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/winstonbonaparte/archive/2009/05/19/4200623.aspx

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多