0

I use a TPaintBox inside my application. Several mouse event handlers are already set up: mouse down, mouse up, etc. However, I also want to respond to keyboard input: if the user presses any function key, I would like to execute a separate procedure (event handler) and not the Mouse* event handler functions. But I also need the mouse position inside my new procedure.

How do I code this, as TPaintBox does not support any key press events?

procedure TForm1.PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  //  here some code
end;

procedure TForm1.PaintBox1MouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
begin
  //  more code here
end;

procedure TForm1.PaintBox1MouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  // here other code
end;
David
  • 13,360
  • 7
  • 66
  • 130
Franz
  • 1,883
  • 26
  • 47

1 Answers1

8

TPaintBox does not descend from TWinControl, but rather from TGraphicControl, which means that it cannot receive input focus and so it has no functionality to react to keyboard events.

Possible solutions:

  • Implement the OnKeyPress event of the parent form on which the PaintBox resides and enable the form's KeyPreview property.
  • Add an action with the specific key press set as its ShortCut property and implement its OnExecute event handler. (See also: When does a ShortCut fire?).
  • Implement an OnShortCut event handler for the MainForm or the Application.
  • Place and align the PaintBox on to a TWinControl and implement the OnKeyPress event of that container.

For combinations of mouse and keyboard input, check the Shift parameter of the mouse events or use the Win32 GetKeyState() and GetKeyboardState() functions.

Community
  • 1
  • 1
NGLN
  • 43,011
  • 8
  • 105
  • 200
  • 1
    I would vote for the last option, more specifically: put the paintbox on a frame. That way you can use the designer in the IDE and still reuse the frame on other forms in the project. – Ondrej Kelle May 25 '15 at 08:29