How to handle the focus of TCastleControlBase

These notes are interesting to you only if you use TCastleControlBase and some other key-handling control on the same Lazarus form.

Like every proper Lazarus control, our TCastleControlBase receives the keys only when it has focus. The control does not capture all the keys pressed over the form (this would be bad, as other controls, maybe even other TCastleControlBase on the same form, may want to handle them). To make sure that controlling the camera by keys (arrow keys, and/or AWSD and other keys, more about keys later) works, make sure that your control has a focus.

In the simplest case, just call


whenever you want.

There's no visual indicator when TCastleControlBase has focus (as there's no standard way to show it, that would be pleasing for various game applications).

How you deal with focus really depends on your application:

  1. In the simplest cases, the problem simply doesn't exist, as TCastleControlBase is the only thing on your form able to receive focus — so it always has focus. All other components on this Lazarus form (if any) are unfocusable, like TSpeedButton.

  2. If you want to use other focusable controls, it's really up to you how to present it to user. In principle, you don't have to do anything, focus works, and it can be switched into/out of TCastleControlBase by the Tab key or clicking with mouse on other controls.

    1. You may want to create a special key shortcut to quickly shift focus to your control (calling Control.SetFocus).

    2. You may want to draw some visual indication, like a border around TCastleControlBase, when it's focused. Actually, our TCastleControlBase may contain inside our own controls (TUIControl class), so you may want to draw TUIControl that is focused (see examples/3d_rendering_processing/multiple_viewports.lpr for simple example that shows which viewport is active, having 4 viewports within a single OpenGL context).

    3. Finally, if you really want, you can also use standard Lazarus features like TForm.KeyPreview and TForm.OnKeyDown / TForm.OnKeyUp to capture some keys at form level and pass them directly to chosen control.