RAD Studio
ContentsIndex
PreviousUpNext
Responding to Key-down Messages

A KeyDown method is a protected method for a control's OnKeyDown event. The control itself calls KeyDown in response to a Windows key-down message. When overriding the inherited KeyDown method, you can include code that provides other responses in addition to calling the OnKeyDown event.

To override KeyDown, follow these steps:

  1. Add a KeyDown method to the TDBCalendar class:

type
  TDBCalendar = class(TSampleCalendar);
   .
   .
   .
  protected
    procedure KeyDown(var Key: Word; Shift: TShiftState; X: Integer; Y: Integer);
      override;
   .
   .
   .
  end;

 

class PACKAGE TDBCalendar : public TSampleCalendar
{
   .
   .
   .
protected:
    virtual void __fastcall KeyDown(unsigned short &Key,  TShiftState Shift);
   .
   .
   .
};

  1. Implement the KeyDown method:

procedure KeyDown(var Key: Word; Shift: TShiftState);
var
  MyKeyDown: TKeyEvent;
begin
  if not ReadOnly and (Key in [VK_UP, VK_DOWN, VK_LEFT, VK_RIGHT, VK_END,
    VK_HOME, VK_PRIOR, VK_NEXT]) and FDataLink.Edit then
    inherited KeyDown(Key, Shift)
  else
  begin
    MyKeyDown := OnKeyDown;
    if Assigned(MyKeyDown) then MyKeyDown(Self, Key, Shift);
  end;
end;

 

void __fastcall TDBCalendar::KeyDown(unsigned short &Key,  TShiftState Shift)
{
  TKeyEvent MyKeyDown;                                // declare event type
  Set<unsigned short,0,8> keySet;                               
  keySet = keySet << VK_UP << VK_DOWN << VK_LEFT      // assign virtual keys to set
    << VK_RIGHT << VK_END << VK_HOME << VK_PRIOR << VK_NEXT;                           
  if (!FReadOnly &&                              // if control is not read only...
      (keySet.Contains(Key)) &&                   // ...and key is in the set...       
      FDataLink->Edit() )                         // ...and field is in edit mode
  {
    TCustomGrid::KeyDown(Key, Shift);          // call the inherited KeyDown method
  }
  else
  {
    MyKeyDown = OnKeyDown;                            // assign OnKeyDown event
    if (MyKeyDown != NULL) MyKeyDown(this,Key,Shift); // execute code in...
  }                                                      // ...OnKeyDown event handler
}

When KeyDown responds to a mouse-down message, the inherited KeyDown method is called only if the control's ReadOnly property is False, the key pressed is one of the cursor control keys, and the data link object is in edit mode, which means the field can be edited. If the field cannot be edited or some other key is pressed, the code the programmer put in the OnKeyDown event handler, if one exists, is executed.

Copyright(C) 2008 CodeGear(TM). All Rights Reserved.
What do you think about this topic? Send feedback!