dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Moving paint object with keyboard input

  1. #1
    Join Date
    Apr 2012
    Posts
    7

    Moving paint object with keyboard input

    Hi Every one

    I have drawn a square on the screen/form using GDI. Now I want to move this object around using keyboard inputs. I just want it to move along the x-axis using left and right arrow keys. I can assign the keys but the problem is making that object move. Please help me on this

  2. #2
    Join Date
    Nov 2007
    Posts
    613

    Re: Moving paint object with keyboard input

    I'll explain what you need to do if the user presses the "right arrow" key. For the other keys you'll need a similar approach.

    1. You need a variable to store the current value of the position of your rectangle (a point for top left corner). The variable must be accessible for all the message handlers described below.

    2. You need the code that draws the rectangle at the current position in the WM_PAINT message handler.

    3.1 You do the seubsequent operations in the handler of the "right arrow" key:
    a. Copy the current position to a temporary variable to be able to retrieve it later.
    b. Modify the current position of the rectangle by adding a small increment to the x coordinate of the point (moving to right).
    c. Before going any further check if the rectangle will not go out of the boundaries of the window. If it goes out, restore the old value of the current position and return taking no action. The user will notice that he cannot move the rectangle out of the window.
    d. If the new coordinates are ok, calculate the smallest rectangle that holds both the old rectangle and the new rectangle (UnionRect). Invalidate that rectangle. The rest is not your business, the WM_PAINT handler will take care to redraw the rectangle at the new position.
    Explanation: The union of the rectangles holds both the old and the new rectangle. The presence of the old rectangle in the union ensures that no longer needed portions of the old rectangle will be removed and, in the same time, the presence of the new rectangle in the union ensures that the new portions of the rectangle not present before will be drawn as necessary.

    4. Don't forget to handle the case when the user resizes the window. Your rectangle may be left in a position outside the window. You need to handle the WM_SIZE message and, if needed, move the rectangle to an acceptable position using the technique described above.
    Last edited by srelu; May 3rd, 2012 at 09:21 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)