Reputation: 27276
I'm building an editor which uses a TImage to display a picture and has mouse events to be able to draw, move, and resize boxes on the image. All this works perfectly. Now I'm trying to implement the ability to use the arrows on the keyboard to move the selected box, but A) TImage does not get any focus, and B) TImage does not have any key events (because it cannot get focus). I guess I could cheat and switch on the form's KeyPreview property and catch them there, but there's many other controls on this form and I'd need to make sure the user is intending to work with the image. For example, if user has focus in the TEdit control, the arrow keys shall only affect this memo, and not modifying the image.
So is there any way to put or fake some kind of focus in the TImage to recognize key events?
Upvotes: 1
Views: 2218
Reputation: 76547
Only controls that inherit from TWinControl
can receive keyboard focus.
TImage
descents from TGraphicControl
and cannot receive keyboard events.
You can put the Image on top of a panel which sits on top of another control e.g. TEdit and give that focus if the Image is selected.
Then just use the OnKeyPress
event of the non-visible edit.
Make sure to disallow the tab key if you don't want that to change the focus to another control.
procedure TForm8.Image1Click(Sender: TObject);
begin
Edit1.SetFocus;
end;
procedure TForm8.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if Key = #9 then Key = #0; //disable tab key.
case key of
//do stuff here
end; {case}
end;
Upvotes: 4