德尔福 - 如果跳到外面的话

时间:2013-03-02 01:41:30

标签: delphi

我使用此代码测试同时按下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;

在代码If中注释跳转到设置FValidKeyCombo值的第30行 当我按下Alt + W + E时会发生这种情况!!为什么??

1 个答案:

答案 0 :(得分:0)

您的代码正常。

我的猜测是,您可能偶然 ;和下一个btn2.OnClick()声明之间引入了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;