MFC定時器使用--SetTimer && KillTimer && 進度條CProgressCtrl

來源:互聯網
上載者:User

這裡以進度條為執行個體,來使用MFC的定時器。

用SetTimer函數 建立定時器

先看一個執行個體,啟動計時器,在類結構裡面定義定時器id:

class CDlgOncloseDlg : public CDialogEx{// Constructionpublic:CDlgOncloseDlg(CWnd* pParent = NULL);// standard constructor// Dialog Dataenum { IDD = IDD_DLGONCLOSE_DIALOG };    enum    {        ID_TIMER_1 = 100,        ID_TIMER_2 = 101,    };

然後再你需要的時機依次啟動各個計時器:  

BOOL CDlgOncloseDlg::OnInitDialog(){CDialogEx::OnInitDialog();// Add "About..." menu item to system menu.// TODO: Add extra initialization here    this->SetTimer(ID_TIMER_1, 5000, NULL);

然後重寫OnTimer,OnTimer函數中這樣寫:  

void CDlgOncloseDlg::OnTimer(UINT_PTR nIDEvent){    // TODO: Add your message handler code here and/or call default    switch(nIDEvent)    {    default:        break;    case ID_TIMER_1:        PostMessage(WM_CLOSE);        break;    }    CDialogEx::OnTimer(nIDEvent);}
SetTimer函數的用法

1)  函數原型及變形

Creates a timer event. UINT SetTimer(   UINT nIDEvent,   UINT nElapse,   void ( CALLBACK* lpfnTimer )(HWND, UINT, UINT, DWORD) = NULL ) throw(); 

注意:設定第二個參數時要注意,如果設定的等待時間比處理時間短,程式就會出問題了。
2)函數產生方法在ClassWizard裡,選擇需要計時器的類,添加WM_TIME訊息映射,就自動產生onTime函數了。然後在函數裡添加代碼,讓代碼實現功能。
每隔一段時間就會自動執行一次。

3) 回呼函數的格式
void CALLBACK TimerProc(HWND hWnd,UINT nMsg,UINT nTimerid,DWORD dwTime);

KillTimer

取消定時器不再使用定時器後,我們應該調用KillTimer來取消定時。

Destroys a timer event created by CWindow::SetTimer. BOOL KillTimer(   UINT nIDEvent ) throw(); 
定時器執行個體,操作一個進度條控制項

在類裡添加一個進度條以及計數:

    CProgressCtrl m_Process;    int count;

然後,初始化範圍和步進值:

    this->SetTimer(ID_TIMER_1, 1000, NULL);    m_Process.SetRange(0, 100);    m_Process.SetStep(10);    count = 0;

再修改定時器處理函數:

void CDlgOncloseDlg::OnTimer(UINT_PTR nIDEvent){    // TODO: Add your message handler code here and/or call default    switch(nIDEvent)    {    default:        break;    case ID_TIMER_1:        //PostMessage(WM_CLOSE);        count++;        TRACE("count is %d", count);        m_Process.StepIt();        int pos = m_Process.GetPos();        if(pos >= 100)        {            PostMessage(WM_CLOSE);        }        break;    }    CDialogEx::OnTimer(nIDEvent);}

也就是說10s之後,進度條滿,ok,關閉對話方塊。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.