Share via


타이머 사용

이 항목에서는 타이머를 만들고 삭제하는 방법과 타이머를 사용하여 지정된 간격으로 마우스 입력을 트래핑하는 방법을 보여 줍니다.

이 항목에는 다음과 같은 섹션이 포함되어 있습니다.

타이머 만들기

다음 예제에서는 SetTimer 함수를 사용하여 두 개의 타이머를 만듭니다. 첫 번째 타이머는 10초마다, 두 번째 타이머는 5분마다 설정됩니다.

// Set two timers. 
 
SetTimer(hwnd,             // handle to main window 
    IDT_TIMER1,            // timer identifier 
    10000,                 // 10-second interval 
    (TIMERPROC) NULL);     // no timer callback 
 
SetTimer(hwnd,             // handle to main window 
    IDT_TIMER2,            // timer identifier 
    300000,                // five-minute interval 
    (TIMERPROC) NULL);     // no timer callback 

이러한 타이머에서 생성된 WM_TIMER 메시지를 처리하려면 hwnd 매개 변수의 창 프로시저에 WM_TIMER 사례 문을 추가합니다.

case WM_TIMER: 
 
    switch (wParam) 
    { 
        case IDT_TIMER1: 
            // process the 10-second timer 
 
             return 0; 
 
        case IDT_TIMER2: 
            // process the five-minute timer 

            return 0; 
    } 

또한 애플리케이션은 타이머를 만들고 myTimerProc 콜백 함수를 사용하여 타이머의 WM_TIMER 메시지를 처리하는 다음 코드 샘플과 같이 기본 창 프로시저가 아니라 애플리케이션에서 정의한 콜백 함수로 WM_TIMER 메시지를 처리하는 타이머를 만들 수도 있습니다.

// Set the timer. 
 
SetTimer(hwnd,                // handle to main window 
    IDT_TIMER3,               // timer identifier 
    5000,                     // 5-second interval 
    (TIMERPROC) MyTimerProc); // timer callback

MyTimerProc에 대한 호출 규칙은 TimerProc 콜백 함수를 기반으로 해야 합니다.

애플리케이션에서 창 핸들을 지정하지 않고 타이머를 만드는 경우 애플리케이션은 메시지 큐에서 WM_TIMER 메시지를 모니터링하고 해당 창으로 디스패치해야 합니다.

HWND hwndTimer;   // handle to window for timer messages 
MSG msg;          // message structure 
 
    while (GetMessage(&msg, // message structure 
            NULL,           // handle to window to receive the message 
               0,           // lowest message to examine 
               0))          // highest message to examine 
    { 
 
        // Post WM_TIMER messages to the hwndTimer procedure. 
 
        if (msg.message == WM_TIMER) 
        { 
            msg.hwnd = hwndTimer; 
        } 
 
        TranslateMessage(&msg); // translates virtual-key codes 
        DispatchMessage(&msg);  // dispatches message to window 
    } 

타이머 삭제

애플리케이션은 KillTimer 함수를 사용하여 더 이상 필요하지 않은 타이머를 삭제해야 합니다. 다음 예제에서는 상수 IDT_TIMER1, IDT_TIMER2 및 IDT_TIMER3 식별된 타이머를 삭제합니다.

// Destroy the timers. 
 
KillTimer(hwnd, IDT_TIMER1); 
KillTimer(hwnd, IDT_TIMER2); 
KillTimer(hwnd, IDT_TIMER3); 

타이머 함수를 사용하여 마우스 입력 트래핑

화면에 마우스 포인터가 있는 동안 더 많은 입력을 방지해야 하는 경우가 있습니다. 이 작업을 수행하는 한 가지 방법은 특정 이벤트가 발생할 때까지 마우스 입력을 트래핑하는 특수 루틴을 만드는 것입니다. 많은 개발자들은 이 루틴을 "마우스트랩 빌드"라고 합니다.

다음 예제에서는 SetTimerKillTimer 함수를 사용하여 마우스 입력을 트래핑합니다. SetTimer 는 10초마다 WM_TIMER 메시지를 보내는 타이머를 만듭니다. 애플리케이션이 WM_TIMER 메시지를 받을 때마다 마우스 포인터 위치를 기록합니다. 현재 위치가 이전 위치와 동일하고 애플리케이션의 기본 창이 최소화되면 애플리케이션은 마우스 포인터를 아이콘으로 이동합니다. 애플리케이션이 닫히면 KillTimer가 타이머를 중지합니다.

HICON hIcon1;               // icon handle 
POINT ptOld;                // previous cursor location 
UINT uResult;               // SetTimer's return value 
HINSTANCE hinstance;        // handle to current instance 
 
//
// Perform application initialization here. 
//
 
wc.hIcon = LoadIcon(hinstance, MAKEINTRESOURCE(400)); 
wc.hCursor = LoadCursor(hinstance, MAKEINTRESOURCE(200)); 
 
// Record the initial cursor position. 
 
GetCursorPos(&ptOld); 
 
// Set the timer for the mousetrap. 
 
uResult = SetTimer(hwnd,             // handle to main window 
    IDT_MOUSETRAP,                   // timer identifier 
    10000,                           // 10-second interval 
    (TIMERPROC) NULL);               // no timer callback 
 
if (uResult == 0) 
{ 
    ErrorHandler("No timer is available."); 
} 
 
LONG APIENTRY MainWndProc( 
    HWND hwnd,          // handle to main window 
    UINT message,       // type of message 
    WPARAM  wParam,     // additional information 
    LPARAM  lParam)     // additional information 
{ 
 
    HDC hdc;        // handle to device context 
    POINT pt;       // current cursor location 
    RECT rc;        // location of minimized window 
 
    switch (message) 
    { 
        //
        // Process other messages. 
        // 
 
        case WM_TIMER: 
        // If the window is minimized, compare the current 
        // cursor position with the one from 10 seconds 
        // earlier. If the cursor position has not changed, 
        // move the cursor to the icon. 
 
            if (IsIconic(hwnd)) 
            { 
                GetCursorPos(&pt); 
 
                if ((pt.x == ptOld.x) && (pt.y == ptOld.y)) 
                { 
                    GetWindowRect(hwnd, &rc); 
                    SetCursorPos(rc.left, rc.top); 
                } 
                else 
                { 
                    ptOld.x = pt.x; 
                    ptOld.y = pt.y; 
                } 
            } 
 
            return 0; 
 
        case WM_DESTROY: 
 
        // Destroy the timer. 
 
            KillTimer(hwnd, IDT_MOUSETRAP); 
            PostQuitMessage(0); 
            break; 
 
        //
        // Process other messages. 
        // 
 
} 

다음 예제에서는 마우스 입력을 트래핑하는 방법도 보여 주지만 애플리케이션 의 메시지 큐 가 아닌 애플리케이션 정의 콜백 함수 MyTimerProc을 통해 WM_TIMER 메시지를 처리합니다.

UINT uResult;               // SetTimer's return value 
HICON hIcon1;               // icon handle 
POINT ptOld;                // previous cursor location 
HINSTANCE hinstance;        // handle to current instance 
 
//
// Perform application initialization here. 
//
 
wc.hIcon = LoadIcon(hinstance, MAKEINTRESOURCE(400)); 
wc.hCursor = LoadCursor(hinstance, MAKEINTRESOURCE(200)); 
 
// Record the current cursor position. 
 
GetCursorPos(&ptOld); 
 
// Set the timer for the mousetrap. 
 
uResult = SetTimer(hwnd,      // handle to main window 
    IDT_MOUSETRAP,            // timer identifier 
    10000,                    // 10-second interval 
    (TIMERPROC) MyTimerProc); // timer callback 
 
if (uResult == 0) 
{ 
    ErrorHandler("No timer is available."); 
} 
 
LONG APIENTRY MainWndProc( 
    HWND hwnd,          // handle to main window 
    UINT message,       // type of message 
    WPARAM  wParam,     // additional information 
    LPARAM   lParam)    // additional information 
{ 
 
    HDC hdc;            // handle to device context 
 
    switch (message) 
    { 
    // 
    // Process other messages. 
    // 
 
        case WM_DESTROY: 
        // Destroy the timer. 
 
            KillTimer(hwnd, IDT_MOUSETRAP); 
            PostQuitMessage(0); 
            break; 
 
        //
        // Process other messages. 
        // 
 
} 
 
// MyTimerProc is an application-defined callback function that 
// processes WM_TIMER messages. 
 
VOID CALLBACK MyTimerProc( 
    HWND hwnd,        // handle to window for timer messages 
    UINT message,     // WM_TIMER message 
    UINT idTimer,     // timer identifier 
    DWORD dwTime)     // current system time 
{ 
 
    RECT rc; 
    POINT pt; 
 
    // If the window is minimized, compare the current 
    // cursor position with the one from 10 seconds earlier. 
    // If the cursor position has not changed, move the 
    // cursor to the icon. 
 
    if (IsIconic(hwnd)) 
    { 
        GetCursorPos(&pt); 
 
        if ((pt.x == ptOld.x) && (pt.y == ptOld.y)) 
        { 
            GetWindowRect(hwnd, &rc); 
            SetCursorPos(rc.left, rc.top); 
        } 
        else 
        { 
            ptOld.x = pt.x; 
            ptOld.y = pt.y; 
        } 
    } 
} 

타이머 정보