如何以编程方式缓慢移动窗口,就好像用户正在这样做?

2 c c++ winapi

我知道MoveWindow()和SetWindowPos()函数.我知道如何正确使用它们.但是,我想要完成的是缓慢平滑地移动窗口,就好像用户正在拖动窗口一样.

我还没有让它正常工作.我尝试的是使用GetWindowRect()获取当前坐标,然后使用setwindow和movewindow函数,每次调用右递增10个像素.

有任何想法吗?

这是我所有定义旁边的内容.

while(1)
{
     GetWindowRect(notepad,&window);

     Sleep(1000);
     SetWindowPos(
        notepad,
        HWND_TOPMOST,
        window.top - 10,
        window.right,
        400,
        400,
        TRUE
        );
}
Run Code Online (Sandbox Code Playgroud)

Sho*_*og9 5

如果你想要流畅的动画,你需要让它基于时间,并允许Windows在两个动作之间处理消息.设置计时器,并根据动画开始后经过的时间将窗口移动一段距离来响应WM_TIMER通知.对于看起来很自然的动作,不要使用线性函数来确定距离 - 而是尝试类似Robert Harvey建议的功能.

伪代码:

//
// animate as a function of time - could use something else, but time is nice.
lengthInMS = 10*1000; // ten second animation length
StartAnimation(desiredPos)
{
   originalPos = GetWindowPos();
   startTime = GetTickCount();
   // omitted: hwnd, ID - you'll call SetTimer differently 
   // based on whether or not you have a window of your own
   timerID = SetTimer(30, callback); 
}

callback()
{
   elapsed = GetTickCount()-startTime;
   if ( elapsed >= lengthInMS )
   {
      // done - move to destination and stop animation timer.
      MoveWindow(desiredPos);
      KillTimer(timerID);
   }

   // convert elapsed time into a value between 0 and 1
   pos = elapsed / lengthInMS; 

   // use Harvey's function to provide smooth movement between original 
   // and desired position
   newPos.x = originalPos.x*(1-SmoothMoveELX(pos)) 
                  + desiredPos.x*SmoothMoveELX(pos);
   newPos.y = originalPos.y*(1-SmoothMoveELX(pos)) 
                  + desiredPos.y*SmoothMoveELX(pos);       
   MoveWindow(newPos);
}
Run Code Online (Sandbox Code Playgroud)