KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Move objects on a form at runtime
PRODUCT: 4D | VERSION: 14.0 | PLATFORM: Mac & Win
Published On: June 19, 2014

It is possible to move an object in a form at runtime. By reading in the movements of a mouse pointer and clicks using GET MOUSE, a reference is made in which the OBJECT MOVE command can change the object's position. Here are code samples to implement:

Code to read the mouse in a form method:

C_LONGINT(x;y;mbutton) // Mouse X, Y, and click state
C_LONGINT(temp_x_movement) // Mouse movement in X
C_LONGINT(temp_y_movement) // Mouse movement in Y

Case of
   : (Form event=On Load)
   ARRAY LONGINT($value;3)
   $value{1}:=On Mouse Enter // Event On Mouse Enter
   $value{2}:=On Mouse Leave // Event On Mouse Leave
   $value{3}:=On Mouse Move // Event On Mouse Move
   OBJECT SET EVENTS(*;"@";$value;Enable events others unchanged) // Set all objects in form to mouse events
   OBJECT SET EVENTS(*;OBJECT Get name(Object current);$value;Enable events others unchanged) // Set form to mouse events

   : (Form event=On Mouse Leave)
   SET TIMER(0)

   : (Form event=On Mouse Enter)
   SET TIMER(1)

   : (Form event=On Timer)
   GET MOUSE(x;y;mbutton)
End case



The move_obj_at_runtime method is placed in the object's method:

// Name: move_obj_at_runtime
//
// Description: Moves an object that is in focus
// of a form using the X, Y, and clicks of GET MOUSE
// at run time.
// (Note process variables x, y, mbutton,
// temp_x_movement, temp_y_movement, are intialized
// in the parent form method)
// ---------------------------------------------------

C_LONGINT($left;$top;$right;$bottom;$avg;$avg_x;$avg_y)
C_TEXT($obj_name)

$obj_name:=OBJECT Get name(Object current)

Case of

   : (Form event=On Mouse Enter)
   OBJECT SET ENABLED(*;$obj_name;False)

   : (Form event=On Mouse Move)
   OBJECT GET COORDINATES(*;$obj_name;$left;$top;$right;$bottom)


   If (mbutton=1) // left click on the mouse hold down to move the object
       // Moving Both X and Y
      If ((temp_x_movement>=$left) & (temp_x_movement<=$right) & (temp_y_movement>=$top) & (temp_y_movement<=$bottom))
         $avg_x:=(($right-$left)/2)+$left
         $avg_y:=(($top-$bottom)/2)+$top

         If ((temp_x_movement>$avg_x) & (temp_y_movement>$avg_y))
            OBJECT MOVE(*;$obj_name;-(temp_x_movement-x);-(temp_y_movement-y);0;0) // Move left

         Else
            OBJECT MOVE(*;$obj_name;x-temp_x_movement;y-temp_y_movement;0;0) // Move right
         End if

      End if

   End if

   : (Form event=On Mouse Leave)
   OBJECT SET ENABLED(*;$obj_name;True)

End case

temp_x_movement:=x
temp_y_movement:=y


Example below shows a sample form with a button being moved while holding the left mouse button:



See Also: