65.9K
CodeProject is changing. Read more.
Home

A 'mouse repeat' function

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.67/5 (3 votes)

Apr 9, 2000

viewsIcon

58573

A function that simulates the keyboard repeat behavior for mouse clicks

This executes DoClickThing() (any function you wish to have called on a WM_LBUTTONDOWN message) as long as

  1. the mouse button is down and
  2. the mouse pointer remains within myRect.

You need to override your OnLButtonDown, OnMouseMove, OnLButtonUp and OnTimer overrides in your CWnd derived class. The repeat rate is set to simulate the keyboard repeat behavior.

Thanks to Christian Sloper for the idea.

void CTestCtrl::OnLButtonDown(UINT nFlags, CPoint point)
{
    if(PtInRect(&myRect, point))
    {
        DoClickThing();
        SetCapture();

        // initial timer interval = keyboard repeat delay
        int setting = 0;
        SystemParametersInfo(SPI_GETKEYBOARDDELAY, 0, &setting, 0);
        int interval = (setting + 1) * 250;
        TimerID = SetTimer(99, interval, NULL);
        TimerStep = 1;
    }
}

void CTestCtrl::OnMouseMove(UINT nFlags, CPoint point)
{
    if(TimerStep && !PtInRect(&myRect, point))
    {
        KillTimer(TimerID);
        ReleaseCapture();
        TimerStep = 0;
    }
}

void CTestCtrl::OnLButtonUp(UINT nFlags, CPoint point)
{
    if(TimerStep)
    {
        KillTimer(TimerID);
        ReleaseCapture();
        TimerStep = 0;
    }
}

void CTestCtrl::OnTimer(UINT nIDEvent)
{
    if(TimerStep == 1)
    {
        KillTimer(TimerID);

        // set timer interval per keyboard repeat rate
        DWORD setting = 0;
        SystemParametersInfo(SPI_GETKEYBOARDSPEED, 0, &setting, 0);
        int interval = 400 - (setting * 12);
        TimerID = SetTimer(100, interval, NULL);
        TimerStep = 2;
    }

    if(TimerStep)
        DoClickThing();
}