Delphi中实现程序的延时的方法
在Delphi中,通常可以用以下三种方法来实现程序的延时,即TTtimer控件,Sleep函数,GetTickCount函数。但是其精度是各不相同的。
一、三种方法的简单介绍
1)TTtimer控件
TTtimer控件的实质是调用Windows API定时函数SetTimer和KillTimer来实现的,并简化了对WM_TIMER 消息的处理过程。通过设置OnTimer事
件和Interval属性,我们可以很方便的产生一些简单的定时事件。
2)Sleep函数
Sleep函数用来使程序的执行延时给定的时间值。Sleep的调用形式为Sleep(milliseconds),暂停当前的进程milliseconds毫秒。Sleep的实现
方法其实也是调用Windows API的Sleep函数。例如:
sleep(1000); //延迟1000毫秒
Sleep会引起程序停滞,如果你延迟的时间较长的话,你的程序将不能够响应延时期间的发生的其他消息,所以程序看起来好像暂时死机。
3)GetTickCount函数
在主程序中延时,为了达到延时和响应消息这两个目的,GetTickCount()构成的循环就是一种广为流传的方法。例如:
procedure Delay(MSecs: Longint);
//延时函数,MSecs单位为毫秒(千分之1秒)
var
FirstTickCount, Now: Longint;
begin
FirstTickCount := GetTickCount();
repeat
Application.ProcessMessages;
Now := GetTickCount();
until (Now - FirstTickCount >= MSecs) or (Now < FirstTickCount);
end;
二、高精度的微妙级性能计数器(high-resolution performance counter)介绍
为了比较以上方法的精度,首先需要找到一个参考的定时器。在这里,我提供了两个参考的定时器。一是用单片机每隔1.024ms产生一个实时
中断RTI,作为计数器;二是选用了一个高精度的微妙级性能计数器(参见:
http://msdn.microsoft.com/msdnmag/issues/04/03/HighResolutionTimer/default.aspx ,或者
http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=200249
)
1)计数器的Delphi源代码
{
A high-precision counter/timer. Retrieves time differences
downto microsec.
Quick Reference:
相关文档:
{ Private declarations }
procedure WMSysCommand (var Msg: TWMSysCommand) ; message WM_SYSCOMMAND;
procedure TForm1.WMSysCommand(var Msg: TWMSysCommand);
begin
if Msg.CmdType = SC_RESTORE then
begin
ShowMessage('SC_RESTORE');
if self.WindowState = wsMaximized then
begin
......
DELPHI中操作ACCESS数据库(建立.mdb文件,压缩数据库)
以下代码在WIN2K,D6,MDAC2.6下测试通过,
编译好的程序在WIN98第二版无ACCESS环境下运行成功.
//声明连接字符串
Const
SConnectionString
= 'Provider=M ......
uses WinInet;
procedure TForm1.Button1Click(Sender: TObject);
begin
if InternetGetConnectedState(nil, 0) then
ShowMessage('已连接')
else
ShowMessage('已断开');
end; ......
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
&n ......
interface
uses Windows, Messages, SysUtils, Classes, Graphics, Controls,
Forms, Dialogs, ExtCtrls, StdCtrls, Buttons;
type
TDemoForm = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
GetButton: TBitBtn;
CloseButton: TBitBtn;
Bevel1: TBevel;
Label5: TLabel;
......