{
  Autor: Michael Springwald
  Datum: Montag, 30.Juli.2007

  Updates: Donnerstag, 16.Augst.2007, Freitag, 17.Augst.2007

  
  Dieses Unit/Klasse soll den Fehler beim Mainmenu beheben
}
unit umenukey;

{$mode objfpc}{$H+}

interface

uses
  Classes, SysUtils,Forms, Menus,LCLType,LCLProc,Controls;

type

  { TMenuKey }

  TMenuKey = class
  private
    fForm:TForm;
  protected

  public
    keyStr,shiftstr:string;
    BackupKeyDown,BackupKeyUp:TKeyEvent;
    procedure KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    constructor Create(aForm:TForm);
    destructor Destroy;

    function FindMenuShortKey(const Key:String):TMenuitem;
  published

end;

implementation

{ TMenuKey }

procedure AddPlus(var str:String);
begin
  if str[Length(str)-1] <> '+' then
    str:=str+'+';
end;

procedure TMenuKey.KeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
   if not (key in [16,17,18]) then begin
     if KeyStr = '' then
       KeyStr:=KeyStr+chr(Key)
     else
       KeyStr:=KeyStr+'+'+chr(Key);
   end;

  if ssCtrl in shift then
    if pos('Ctrl',shiftstr) = 0 then
        shiftstr:=shiftstr+'Ctrl+';

  if 18 = key then
    if pos('Alt',shiftstr) = 0 then
        shiftstr:=shiftstr+'Alt+';

  if ssShift in shift then
    if pos('Shift',shiftstr) = 0 then
      shiftstr:=shiftstr+'Shift+';

  if Assigned(BackupKeyDown) then BackupKeyDown(sender, key, shift);
end;

procedure TMenuKey.KeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  Writeln('"',keystr,'"');
  if KeyStr <> '' then
    FindMenuShortKey(shiftstr + KeyStr);

  KeyStr:=''; shiftstr:='';
  if Assigned(BackupKeyUp) then BackupKeyUp(sender, key, shift);

end;

constructor TMenuKey.Create(aForm: TForm);
begin
  aForm.KeyPreview:=True;

  BackupKeyDown:=aForm.OnKeyDown;
  BackupKeyUp:=aForm.OnKeyUp;

  aForm.OnKeyUp:=@KeyUp;
  aForm.OnKeyDown:=@KeyDown;
  fForm:=aForm;
end;

destructor TMenuKey.Destroy;
begin

end;

function TMenuKey.FindMenuShortKey(const Key:String ): TMenuitem;

  function GetMenu(aMenu:TMenuitem):Boolean;
  var
    i:Integer;
    aKey:Word;
    aShift:TShiftState;
    str:String;
  begin
    for i:=0 to aMenu.Count-1 do begin
      result:=False;
      str:=ShortCutToText(aMenu.Items[i].ShortCut);
      if str = key then begin
        result:=true;
         if Assigned(aMenu.Items[i].OnClick) then
           aMenu.Items[i].OnClick(aMenu.Items[i]);
        break;
      end
      else begin
        if aMenu.items[i].count > 0 then
          getMenu(aMenu[i]);
      end;
    end;
  end;
var
  i:Integer;
begin
  for i:=0 to fForm.Menu.Items.count-1 do begin
    if GetMenu(fForm.Menu.Items[i]) then break;
  end;
end;

end.

