2006. január 15., vasárnap

Write Components which handle ENTER-Key like TAB-Key


Problem/Question/Abstract:

Standard-behaviour of controls when pressing ENTER-KEY is a BEEP-Sound. But how to write Components which handle ENTER-Key like TAB-Key?

Answer:

This Article will show how to write Components which will handle the ENTER-Key in the same behaviour like the TAB-Key. As Sample I will take a TEdit-Component but it should work on oll other components with OnKeyPress-Event.

Create a new Component from TEdit with a new property:

EnterNextCtrl: Boolean

If this is TRUE (standard), the Focus will jump to next Control if the user press ENTER. If it is FALSE it will show standard-behaviour (beep). This functionality is included in OnKeyPress-Event. There the component sends the Message "WM_NextDLGCTL" to the parent Form. It's important to get the ParentForm, because the TMyEdit need not included on TForm directly but maybe on a TPanel. So you have to send the message directly to the parent-FORM (and not to PARENT, which may be a TPanel).

It should be possible to use this way for other components which have a OnKeyPress-Event.

type
  TMyEdit = class(TEdit)
  private
    FEnterNextCtrl: Boolean;
  protected
    procedure KeyPress(var Key: Char); override;
  published
    property EnterNextCtrl: Boolean read FEnterNextCtrl write FEnterNextCtrl;
    constructor Create(AOwner: TComponent); override;
  end;

constructor TMyEdit.Create(AOwner: TComponent);
begin
  inherited;
  FEnterNextCtrl := TRUE;
end;

procedure TMyEdit.KeyPress(var Key: Char);
var
  ParentForm: TCustomForm;
begin
  inherited;
  if key = #13 then
  begin
    Key := #0;

    //Get the parent-Form.
    ParentForm := GetParentForm(self);

    if FEnterNextCtrl = TRUE {//Jump to next Control or beep } then
      parentform.Perform(WM_NextDLGCTL, 0, 0)
    else
      messageBeep(0);
  end;
end;

Nincsenek megjegyzések:

Megjegyzés küldése