How to Move a Control Across a Form at Run Time

Last reviewed: June 21, 1995
Article ID: Q113904
The information in this article applies to:

- Microsoft Visual Basic programming system for Windows,

  versions 1.0, 2.0, and 3.0

SUMMARY

This article shows by example how to use the Move method to move a text box across a form at run time. This is an alternative to the Drag and Drop method. You can alter the example code to move other controls at run time as long as the control has both a Top and Left property to set.

MORE INFORMATION

Example Showing How to Move Text Box Across Form at Run Time

  1. Start a new project in Visual Basic. Form1 is created by default.

  2. Add a Text box (Text1) and Command button (Command1) to the form.

  3. Place the following code in the (general) (declarations) section of Form1:

       Dim moving_flag%   'moving flag to toggle moving ability
    
    

  4. Place the following code in the Command1 Click event procedure of Form1:

       Sub Command1_Click ()
          moving_flag% = 1   'start the text box moving with the mouse
       End Sub
    
    

  5. Place the following code in the Form Load event procedure of Form1:

       Sub Form_Load ()
          moving_flag% = 0   ' Initially set the flag to turn off the moving.
          Command1.Caption = "Turn moving on"
       End Sub
    
    

  6. Place the following code in the Form MouseMove event procedure of Form1:

       ' Enter the following two lines as one, single line:
       Sub Form_MouseMove (Button As Integer, Shift As Integer, x As Single,
          y As Single)
          If moving_flag% = 1 Then   ' Condition to call the moving procedure.
             Text1.Move x, y
          End If
       End Sub
    
    

  7. Place the following code in the Text1 Click event:

       Sub Text1_Click ()
          moving_flag% = 0
       End Sub
    
    

  8. From the Run menu, choose Start (ALT, R, S), or press the F5 key to run the program. Click the Command1 button. Then click within the Text1 box to stop the moving.


Additional reference words: 1.00 2.00 3.00
KBCategory: kbprg kbcode
KBSubcategory: PrgCtrlsStd


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: June 21, 1995
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.