Qt Windows下多媒體計時器使用舉例

來源:互聯網
上載者:User


在QTimer源碼分析(以Windows下實現為例)
一文中,我們看到了Qt在windows下對計時器的使用:

  • 對於間隔為零的情況,Qt並沒有動用系統的計時器
  • 對於間隔非零的情況
    • 間隔小於20ms 且系統支援多媒體計時器,則使用多媒體計時器
    • 否則,使用普通計時器

Qt 的這種策略應該能很好地滿足我們的需求了,但qtcn上一個網友還是比較期待自己直接調用系統的多媒體計時器。既然這樣,自己還是嘗試寫寫吧,寫一個自己的Timer類

代碼
  • 代碼還是比較簡單的,標頭檔 mmtimer.h 如下:
#ifndef MMTIMER_H#define MMTIMER_H#include <qt_windows.h>#include <QtCore/QObject>class MMTimer : public QObject{    Q_OBJECTpublic:    explicit MMTimer(int interval, QObject *parent = 0);    ~MMTimer();signals:    void timeout();public slots:    void start();    void stop();friend void WINAPI CALLBACK mmtimer_proc(uint, uint, DWORD_PTR, DWORD_PTR, DWORD_PTR);private:    int m_interval;    int m_id;};#endif // MMTIMER_H
  • 源碼檔案 mmtimer.cpp 如下:
#include "mmtimer.h"#include <MMSystem.h>#ifdef __MINGW32__ //w32api bug#define TIME_KILL_SYNCHRONOUS 0x0100#endifvoid WINAPI CALLBACK mmtimer_proc(uint timerId, uint, DWORD_PTR user, DWORD_PTR, DWORD_PTR){    MMTimer *t = reinterpret_cast<MMTimer*>(user);    emit t->timeout();}MMTimer::MMTimer(int interval, QObject *parent) :    QObject(parent),m_interval(interval),m_id(0){}MMTimer::~MMTimer(){    stop();}void MMTimer::start(){    m_id = timeSetEvent(m_interval, 1, mmtimer_proc, (DWORD_PTR)this,                 TIME_CALLBACK_FUNCTION | TIME_PERIODIC | TIME_KILL_SYNCHRONOUS);}void MMTimer::stop(){    if (m_id){        timeKillEvent(m_id);        m_id = 0;    }}
說明

上面的代碼應該不需要什麼解釋了:

  • timeSetEvent 和 timeKillEvent 可直接查閱 MSDN
  • 另外,MinGW的win32api包,對TIME_KILL_SYNCHRONOUS沒有定義,代碼中做了一點修正

請確保正確連結所需要的庫

LIBS += -lwinmm

注意:MSDN 對timeSetEvent的介紹中這麼說的(對此不做評論)

Note  This function is obsolete. New applications should use CreateTimerQueueTimer to create a timer-queue timer.

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.