Timer Events in MFC Applications

Event timers are always handy to have around and useful in nearly every project. When a timer is readily available, such as the Timer control in Visual Basic, you find all kinds of reasons to use one in an application. The lack of a timer object in MFC is, in my opinion, a serious oversight.

Luckily, Microsoft Windows NT/95 systems provide a number of timers for use by application programs. This tutorial provides information on how to install timers in your MFC application, and how to start, process and stop the timers.

In the final section of the tutorial, we develope a simple timer project which is capable of rough animation of an icon in the dialog window. This project is useful in any compute or I/O bound application, and illustrates the techniques involved with installing and using a system timer.

These steps were developed and tested on a WindowsNT 4.0 workstation and Windows95 using VisualC++ 4.2 with Microsoft Foundation Classes.

Installing a Timer

  • In the header file of the dialog using the timer,
  • Add a message number for each timer needed:

    #define

    IDT_TIMER_0

    WM_USER + 200

    #define

    IDT_TIMER_1

    IDT_TIMER_0 + 1

  • Add the timer interrupt handler

    OnTimer (UINT TimerVal)

    to the Generated Message Map:

  • locate the section under Implementation where the AFX_MSG message map is declared (usually begins with the line OnInitDialog());
  • add a line just after the last line in the message map (just before the "//}}AFX_MSG"):

    afx_msg

    void

    OnTimer (UINT TimerVal);

  • This should be the last entry in the message map.
    • In the dialog implementation (.cpp) file,
  • Locate the dialog class start
  • Find the line starting "BEGIN_MESSAGE_MAP"
  • After the last entry in the message map (before the line "//}}AFX_MSG_MAP"), add

    ON_WM_TIMER ( )

    Starting the timer

    To start the timer, you must issue a SetTimer command:

    t-number = SetTimer (t-messaget-interval, NULL)

    where:

    t-message

    The message number assigned for processing the timer request. 
    This is referred to as IDT_TIMER_0 in the installation instructions.

    t-interval

    The timer duration, in mSec.

    t-number

    The system timer number assigned to this event, or 0 if no timers available.

    For Example:

    UINT StartTimer (UINT TimerDuration)

    {

    UINT TimerVal;

    TimerVal = SetTimer (IDT_TIMER_0, TimerDuration, NULL);

    if (TimerVal == 0)

    {

    MessageBox ("Unable to obtain timer",

    "IDT_TIMER_0",

    MB_OK|MB_SYSTEMMODAL);

    }

    return TimerVal;

    }// end StartTimer

    To start the timer, pass it the value of the timer duration, in milliseconds (mSec). If the returned value is non-zero, the timer has been initialized.

    Note: You must save the assigned timer value in order to stop the timer, and also to know which timer to process in a multi-timer application.

    Stopping the Timer

    To stop the timer, issue the KillTimer command:

    t-result = KillTimer (t-number);

    where:

    t-number

    The system timer number from either the SetTimer or OnTimer methods.

    t-result

    The boolean result of the operation, TRUE indicating success.

    For Example:

    BOOL StopTimer (UINT TimerVal)

    {

    //

    // Stop the timer

    //

    if (!KillTimer (TimerVal))

    {

    return FALSE;

    }

    //

    // Place clean-up code following this point.

    //

    return TRUE;

    } // end StopTimer

    Processing Timer Events - The OnTimer Method

    After the timer has been started, the OnTimer event will be called each time the timer counts down to zero (reaches terminal count) from the requested value. This event is asynchronous to the timer - a message is placed in the message queue of the calling process and the timer is automatically restarted.

    The timer can be stopped (refer to Stopping the Timer) upon entry to the OnTimer routine, or left to run if the event will not occur again before processing the OnTimer routine has completed.

    The OnTimer method will be executed each time the timer reaches terminal count. The code in this method should be short and concise; it should be code which must be executed each time the timer reaches its terminal count, such as changing the view of an animated drawing or icon, or setting a flag to process latter, or starting a thread to handle the more complex functions.

    Example:

    void OnTimer (UINT TimerVal)

    {

    //////////////////////////////////////////////

    //

    // Stop the timer

    //

    //////////////////////////////////////////////

    if (!KillTimer (TimerVal))

    {

    }

    //////////////////////////////////////////////

    //

    // Process the event

    //

    //////////////////////////////////////////////

    //////////////////////////////////////////////

    //

    // Restart the timer, if needed, before exiting

    //

    //////////////////////////////////////////////

    }

    Multiple Timers

    The OnTimer method is passed an unsigned integer (UINT) to identify the timer which is interrupting. The value of this timer may be used to stop the associated timer. It can also be used in a multiple timer environment to determine what type of processing must occur.

    Example:

    Assumptions:

    • The timers are started using the example in the section on Installing a Timer.
    • The timer values are placed sequentially into the array ATimer, as follows:
      • ATimer [0] = StartTimer (200); // a 200 mSec timer
      • ATimer [1] = StartTimer (500); // a 500 mSec timer

    void OnTimer (UINT TimerVal)

    {

    int Index;

    /////////////////////////////////////////////////////////////////////////////

    //

    // Check timer number 0

    //

    ////////////////////////////////////////////////////////////////////////////

    if (TimerVal == ATimer[0])

    {

    //

    // Process timer 0 message!

    //

    return;

    }

    ////////////////////////////////////////////////////////////////////////////

    //

    // check timer number 1

    //

    ////////////////////////////////////////////////////////////////////////////

    if (TimerVal == ATimer[1])

    {

    //

    // Process timer 1 message!

    //

    return;

    }

    ////////////////////////////////////////////////////////////////////////////

    //

    // Not timer number 0 or 1

    //

    ////////////////////////////////////////////////////////////////////////////

    if (!KillTimer (TimerVal))

    {

    }

    CString Message;

    Message.format("Unkown timer interrupt: %u", TimerVal);

    MessageBox (Message,"OnTimer",MB_OK|MB_SYSTEMMODAL);

    } // end OnTimer

    From: https://www.developer.com/net/cplus/article.php/603531/Using-Timers-in-MFC-Applications.htm

Using Timers in MFC Applications的更多相关文章

  1. 基于VC的MFC界面开发

    教你熟悉VC6.0创建一个可视化软件的过程 UpdateData(TRUE);//将输入数据赋给文本框变量. UpdateData(FALSE);//将内容显示在文本框中 AfxMessageBox( ...

  2. 区别:Use MFC In A Shared DLL 和 Use MFC In A Static Library

    摘自:Programming Windows with MFC, 2nd Edition Choosing Use MFC In A Shared DLL minimizes your applica ...

  3. 一些非常好的VC++/MFC开源项目链接

    Introduction List of some of the best Open Source projects written in VC++/MFC. Background Codeproje ...

  4. Some Very Good VC++/MFC Resources Besides Codeproject.com

    Some Very Good VC++/MFC Resources Besides Codeproject.com http://www.naughter.com/ (VC++/MFC huge co ...

  5. 基于MFC的Media Player播放器的制作(4---功能实现代码)

    |   版权声明:本文为博主原创文章,未经博主允许不得转载. PandaPlayerDlg.h // PandaPlayerDlg.h : header file // //{{AFX_INCLUDE ...

  6. 第六篇--MFC美化界面

    1.MFC如何设置背景颜色 首先,为对话框添加WM_CTLCOLOR消息,方法为:右击Dialog窗口 --> Class Wizard --> Messages --> WM_CT ...

  7. MFC 学习笔记

    MFC 学习笔记 一.MFC编程基础: 概述: 常用头文件: MFC控制台程序: MFC库程序: 规则库可以被各种程序所调用,扩展库只能被MFC程序调用. MFC窗口程序: 示例: MFC库中类的简介 ...

  8. C++的简单“五子棋”游戏,只是核心代码,资源代码未添加

    ChessBoard.h #ifndef __CHESS_BOARD_H__ #define __CHESS_BOARD_H__ #include "DataStruct.h" # ...

  9. C++ 使用SQLite

    1.SQLite是一个完全独立的.不需要服务器.不要任何配置.支持SQL的.开源的文件数据库引擎.源代码和支持可以登录:http://www.sqlite.org/   1.1.下载sqlite3.d ...

随机推荐

  1. STM32 System and Timer Clock Configurations

    STM32 System and Timer Clock Configurations I've started writing some software to drive a series of  ...

  2. 怎样把XP系统装到USB里?

    怎么样在usb(usb闪存)里面装XP系统? 就是把usb当硬盘用 不买硬盘. U盘肯定装不了系统,装进去了也肯定蓝屏.为什么?因为USB得数据传输太慢,不会超过10M/S的,而你的IDE口或者SAT ...

  3. [Winform]默认以管理员身份运行程序

    摘要 在使用setupfactory打包之后,想让程序默认以管理员身份运行,因为涉及到创建文件删除文件的操作,如果权限比较低的话,会出现没有权限操作的bug. 解决办法 在项目中找到app.manif ...

  4. c编程:输入一个数字n,则n代表n行,每行输入2个数字a,b计算每行的a+b问题。

    输入 第一行输入要计算的数据组数 n 接下来的 n 行,每行包括两个数a和b 输出 每行输出一组数据中a+b的值 例子输入 2 1 2 4 0 例子输出 3 4 代码: #include<std ...

  5. 在ASP.NET MVC中使用Knockout实践03,巧用data参数

    使用Knockout,当通过构造函数创建View Model的时候,构造函数的参数个数很可能是不确定的,于是就有了这样的一个解决方案:向构造函数传递一个object类型的参数data. <inp ...

  6. delphi连接mysql不用添加DSN(mysql connector odbc 5.1版)

    一.下载安装mysql驱动http://mysql.com/downloads/connector/odbc/二.添加adoconnection,adoquery,使用以下连接字符串http://ww ...

  7. poi workbook转成流

    try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); workbook.write(bos); byte[] barray = ...

  8. Python:日期和时间类型学习

    背景 在非开发环境经常需要做一下日期计算,就准备使用Python,顺便记下来学习的痕迹. 代码 1 # coding = utf-8 2 3 from datetime import * 4 5 ## ...

  9. Java POI 3.17写入、导入EXCEL性能测试

    我们先测试一下写入 50000 条 程序源码: 写入的excel文件信息 再看一下文件的结构 我们再次测试一下导入数据库的性能(用移动的网络上传至电信服务器): 在导入的过程中也可以中止导入行为: 上 ...

  10. SharePoint 列表视图修改多行文本字段显示长度

    前言 最近有这么个需求,用户希望在所有项目视图显示多行文本字段,然后,又不希望显示的过场,也就是处理一下长度. 一开始就想到用js的方式去处理,偶然间发现还可以用jslink,尝试了一下,非常好用,分 ...