代码之家  ›  专栏  ›  技术社区  ›  Marus Gradinaru

如何阻止TradioButton对箭头键的反应?

  •  3
  • Marus Gradinaru  · 技术社区  · 6 年前

    我有一个小组 TRadioButton 水平放置。如果最左的按钮是焦点,我按下左箭头,焦点跳到最右的按钮。当所有的箭头到达边缘时,我想停止这种行为。有可能吗? 我试图超越 WM_KEYDOWN 但当按下箭头键时,按钮永远不会收到此消息。

      TRadioButton = class(StdCtrls.TRadioButton)
      protected
        procedure WMKeyDown(var Message: TWMKeyDown); message WM_KEYDOWN;
        procedure WMKeyUp(var Message: TWMKeyUp); message WM_KEYUP;
      public
        BlockLeft, BlockRight: Boolean;
        constructor Create(AOwner: TComponent); override;
      end;
    
    constructor TRadioButton.Create(AOwner: TComponent);
    begin
     inherited;
     BlockLeft:= False;
     BlockRight:= False;
    end;
    
    procedure TRadioButton.WMKeyDown(var Message: TWMKeyDown);
    begin
     if BlockLeft and (Message.CharCode = VK_LEFT) then Exit;
     if BlockRight and (Message.CharCode = VK_RIGHT) then Exit;
    
     inherited;
    end;
    
    procedure TRadioButton.WMKeyUp(var Message: TWMKeyUp);
    begin
     if BlockLeft and (Message.CharCode = VK_LEFT) then Exit;
     if BlockRight and (Message.CharCode = VK_RIGHT) then Exit;
     inherited;
    end;
    
    1 回复  |  直到 6 年前
        1
  •  4
  •   Sertac Akyuz    6 年前

    VCL将键盘消息偏移为 控制通知 并将其发送到消息的预定控件。所以你应该拦截 CN_KEYDOWN 取而代之的是信息。

    如果这是一次性的设计考虑,我更愿意在表单级别处理此行为,因为imo控件本身不应该关心它放在何处。对于希望所有单选按钮的行为都相似的窗体,例如:

    procedure TForm1.CMDialogKey(var Message: TCMDialogKey);
    begin
      if ActiveControl is TRadioButton then
        case Message.CharCode of
          VK_LEFT, VK_UP: begin
            if ActiveControl.Parent.Controls[0] = ActiveControl then begin
              Message.Result := 1;
              Exit;
            end;
          end;
          VK_RIGHT, VK_DOWN: begin
            if ActiveControl.Parent.Controls[ActiveControl.Parent.ControlCount - 1]
                = ActiveControl then begin
              Message.Result := 1;
              Exit;
            end;
          end;
        end;
      inherited;
    end;
    


    如果这不是一次性的行为,我会去写一个容器控件,维多利亚在评论中提到的问题。