0

我使用此代码测试同时按下 3 个字母但IF跳到外面case

....
private
FValidKeyCombo: boolean
....

procedure MyForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  if FValidKeyCombo and (Shift = [ssAlt]) then
    case Key of
      Ord('N'): //New
        if (GetKeyState(Ord('C')) and $80) = $80 then 
          btn1.OnClick(nil)

        else if (GetKeyState(Ord('T')) and $80) = $80 then 
          btn2.OnClick(nil)

        else if (GetKeyState(Ord('Q')) and $80) = $80 then 
          btn3.OnClick(nil)

        else if (GetKeyState(Ord('W')) and $80) = $80 then 
          btn3.OnClick(nil);

     Ord('E'): //New
        if (GetKeyState(Ord('C')) and $80) = $80 then 
          btn1.OnClick(nil)

        else if (GetKeyState(Ord('T')) and $80) = $80 then //<-- after this line if jump to line 30!! why ???
          btn2.OnClick(nil)

        else if (GetKeyState(Ord('Q')) and $80) = $80 then 
          btn3.OnClick(nil)

        else if (GetKeyState(Ord('W')) and $80) = $80 then 
          btn3.OnClick(nil);

  end; //case Key of

{This is line 30}  FValidKeyCombo := (Shift = [ssAlt]) and (Key in [Ord('C'), Ord('T'), Ord('Q'), Ord('W')]);
end;

procedure MyForm.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  FValidKeyCombo := False;
end;

正如代码中注释的那样,当我按下 Alt+W+E 时,会If跳转到设置值的第 30 行!FValidKeyCombo为什么 ??

4

1 回答 1

0

您的代码工作正常。

我的猜测是,您可能不小心;在 thebtn2.OnClick()和 next语句之间引入了 a else,从而终止了您的if语句。它可以编译,因为该case语句也可以包含else一部分,并且您已经处于案例的最后一个值。

为此,我总是将复杂的代码begin/end成对地包围起来,这并不花费任何成本,但却为代码增加了很多清晰度。

例如,我将您的代码更改为:

procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
  Shift: TShiftState);
begin
  if FValidKeyCombo and (Shift = [ssAlt]) then
  begin
    case Key of
      Ord('N'): //New
        begin
          if (GetKeyState(Ord('C')) and $80) = $80 then
            btn1.OnClick(nil)
          else if (GetKeyState(Ord('T')) and $80) = $80 then
            btn2.OnClick(nil)
          else if (GetKeyState(Ord('Q')) and $80) = $80 then
            btn3.OnClick(nil)
          else if (GetKeyState(Ord('W')) and $80) = $80 then
            btn3.OnClick(nil);
        end;
     Ord('E'): //New
       begin
        if (GetKeyState(Ord('C')) and $80) = $80 then
          btn1.OnClick(nil)
        else if (GetKeyState(Ord('T')) and $80) = $80 then
          btn2.OnClick(nil) //a ; here now produces a compiler error
        else if (GetKeyState(Ord('Q')) and $80) = $80 then
          btn3.OnClick(nil)
        else if (GetKeyState(Ord('W')) and $80) = $80 then
          btn3.OnClick(nil);
       end;
    end; //case Key of
  end;
  FValidKeyCombo := (Shift = [ssAlt]) and (Key in [Ord('C'), Ord('T'), Ord('Q'), Ord('W')]);
end;
于 2013-03-02T03:12:48.993 回答