폼이 움이직다가 화면 가장자리에 닿으면 다른 방향으로 튀게 하여 화면 안에서 움직이는 폼을 만들어 보겠습니다.

폼에 타이머를 한개 가져다 두고 아래 코드를 작성하면 됩니다.

화면 가장자리에 닿았는지에 따라 mMoveX와 mMoveY가 다음 이동방향을 결정하는 부분이 중요합니다.



Private mMoveX  As Long

Private mMoveY  As Long


Private Sub Form_Click()

  Unload Me

End Sub


Private Sub Form_Load()


  mMoveX = 1

  mMoveY = 1


  Timer1.Enabled = True

  Timer1.Interval = 1

  

End Sub


Private Sub Timer1_Timer()

  

  Const MoveInterval  As Long = 10

  

  Dim lLeft     As Long

  Dim lTop      As Long

  Dim lRight    As Long

  Dim lBottom   As Long

  


  lLeft = Me.Left

  lTop = Me.Top

  lRight = Me.Left + Me.Width

  lBottom = Me.Top + Me.Height


  

  If lLeft <= 0 Or lRight >= Screen.Width Then

    mMoveX = mMoveX * -1

  End If

  

  If lTop <= 0 Or lBottom >= Screen.Height Then

    mMoveY = mMoveY * -1

  End If

  

  Me.Move Me.Left + (MoveInterval * mMoveX * 15), Me.Top + (MoveInterval * mMoveY * 15)


End Sub



다음은 동일한 기능을 수행하도록 API로 작성해보았습니다.



Private Declare Function GetWindowRect Lib "user32" _

                        (ByVal hwnd As Long, _

                         lpRect As RECT) As Long


Private Declare Function GetClientRect Lib "user32" _

                        (ByVal hwnd As Long, _

                         lpRect As RECT) As Long


Private Declare Function GetDesktopWindow Lib "user32" () As Long


Private Declare Function SetWindowPos Lib "user32" _

                        (ByVal hwnd As Long, _

                         ByVal hWndInsertAfter As Long, _

                         ByVal x As Long, _

                         ByVal y As Long, _

                         ByVal cx As Long, _

                         ByVal cy As Long, _

                         ByVal wFlags As Long) As Long


Private Const SWP_NOSIZE = &H1


Private Type RECT

        Left As Long

        Top As Long

        Right As Long

        Bottom As Long

End Type



Private mMoveX  As Long

Private mMoveY  As Long


Private Sub Form_Click()

  Unload Me

End Sub


Private Sub Form_Load()


  mMoveX = 1

  mMoveY = 1


  Timer1.Enabled = True

  Timer1.Interval = 1

  

End Sub


Private Sub Timer1_Timer()

  

  Const MoveInterval  As Long = 10

  

  Dim ClientRect As RECT

  Dim WindowRect As RECT


  GetClientRect GetDesktopWindow, ClientRect


  GetWindowRect Me.hwnd, WindowRect


  

  If WindowRect.Left <= 0 Or WindowRect.Right >= ClientRect.Right Then

    mMoveX = mMoveX * -1

  End If

  

  If WindowRect.Top <= 0 Or WindowRect.Bottom >= ClientRect.Bottom Then

    mMoveY = mMoveY * -1

  End If

 

  SetWindowPos Me.hwnd, 0&, WindowRect.Left + (MoveInterval * mMoveX), _

                            WindowRect.Top + (MoveInterval * mMoveY), 0, 0, SWP_NOSIZE

  

End Sub


폼에 위치나 크기정보를 가져오기 위해 GetClientRect와 GetWindowRect를 사용하였네요.


폼 위치, 크기 구하기



+ Recent posts