O-Zamzam
O-Zamzam

Reputation: 21

How can I move a control in Delphi at runtime using the keyboard?

I added an option to move a control at runtime with the mouse, based on this and it's working well.

But I was trying to find some code to do the same trick but with the keyboard -- pretty much like moving a component at design time (only moving).

How can this be achieved?

Upvotes: 2

Views: 486

Answers (1)

Andreas Rejbrand
Andreas Rejbrand

Reputation: 109003

This is very easy if you know how to do the different parts of it.

  1. Create a new VCL application.

  2. Drop a TShape on the form.

  3. Add the following OnKeyDown event handler to the form:

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
const
  D = 2;
begin
  case Key of
    VK_UP:
      Shape1.Top := Shape1.Top - D;
    VK_DOWN:
      Shape1.Top := Shape1.Top + D;
    VK_LEFT:
      Shape1.Left := Shape1.Left - D;
    VK_RIGHT:
      Shape1.Left := Shape1.Left + D;
  end;
end;
  1. Run the application.

This being said, however:

Creating animations by moving controls on a form is wrong.

Instead, if you want to create animations, the right thing to do is to draw them manually using GDI, GDI+, OpenGL, or DirectX/Direct2D. Here is my standard example of how to do this.

Upvotes: 4

Related Questions