2016-03-22 37 views
-1

我正在使用settimer來啓動定時器。每當計時器失效時,我都想更改定時器的值。 的代碼如下:無法更改定時器值

#include<iostream> 
#include <windows.h> 
#include <stdio.h> 
#include<WinUser.h> 
#pragma comment(lib, "user32.lib") 


    void main() 
    { 

     int id = 1; 
     static bool isStart = false; 
     static long l = 10000; 
     while(1) 
     { 
      int n; 
      MSG msg = {0}; 

      { 

       SetTimer(NULL, id,l,NULL); 

       while(GetMessage(&msg,NULL, 0,0)) 
       { 
        // Post WM_TIMER messages to the hwndTimer procedure. 
        if (msg.message == WM_TIMER) 
        { 
         std::cout << "Timer expired"; 
         KillTimer(NULL, id); 
         msg.message = 0x0; 
         l = 20000; 
         break; 
        } 
       } 
      } 
     } 

    } 

即使我的值更改爲20000它不是服用,計時器只設置一次。 需要幫助。

感謝

+0

我想你的消息'msg'不會被調度到窗口。爲什麼在'GetMessage'循環不包括'在DispatchMessage(&msg);'? 此外,什麼是的#include ''的需要,當你有'的#include '? – ubuntugod

+0

我用在DispatchMessage(&msg);還是它不工作 – anonymous

+0

哪裏你的WM_TIMER檢查(如果(msg.message == WM_TIMER))在此塊 – ubuntugod

回答

2

您需要使用的SetTimer的返回值來終止計時器

int main(int argc, char **argv) 
{ 
    static bool isStart = false; 
    static long l = 5000; 
    while(1) 
    { 
     int n; 
     MSG msg = {0}; 

     UINT_PTR p = SetTimer(NULL, 0,l,NULL); 

     while(GetMessage(&msg,NULL, 0,0)) 
     { 
    // Post WM_TIMER messages to the hwndTimer procedure. 
      if (msg.message == WM_TIMER) 
      { 
       std::cout << "Timer expired" << std::endl; 
       KillTimer(NULL, p); 
       msg.message = 0x0; 
       l = 20000; 
       break; 
      } 
     } 
    } 
} 

的SetTimer從MSDN

返回值

類型:類型:UINT_PTR如果該函數成功並且hWnd參數爲NULL,返回值爲整數識別新的計時器。一個 應用程序可以將該值傳遞給KillTimer函數以銷燬該定時器。

+0

非常感謝你現在的工作 – anonymous

+1

@Sneha:如果一個答案完全解決了你的問題,你應該接受它,這使未來的訪問者更容易找到合作伙伴正確的解決方案。 – IInspectable

+0

@IInspectable我已經回覆了答案,這個答案很有用,現在正在工作,請參閱評論 – anonymous