How to detect modifier key change in a control which doesn't have focus?

后端 未结 4 1468
故里飘歌
故里飘歌 2020-12-31 07:18

Background:

I\'m working on a control derived from TCustomControl class which can get focus and which has some inner elements inside. Those inner elem

4条回答
  •  独厮守ぢ
    2020-12-31 07:47

    Remy's answer is likely your solution, but in case you're trying to do this without the restriction of encapsulating it into a control and found yourself here:

    You could handle this with a three step process, as I've shown below.

    The key things here are:

    1. Set the control's cursor, not the screen's cursor
    2. Use the form's KeyPreview property
    3. Find the control under the cursor

    I've used a button to illustrate the process. Be sure to set your form's KeyPreview to True.

    procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    var
      myControl: TControl;
    begin
      // If they pressed CTRL while over the control
      if ssCtrl in Shift then
      begin
        myControl := ControlAtPos(ScreenToClient(Mouse.CursorPos), False, True);
        // is handles nil just fine
        if (myControl is TButton) then
        begin
          myControl.Cursor := crSizeAll;
        end;
      end;
    end;
    
    procedure TForm1.FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
    var
      myControl: TControl;
    begin
      // If they released CTRL while over the control
      if not(ssCtrl in Shift) then
      begin
        myControl := ControlAtPos(ScreenToClient(Mouse.CursorPos), False, True);
        if (myControl is TButton) then
        begin
          myControl.Cursor := crDefault;
        end;
      end;
    end;
    
    procedure TForm1.Button1MouseMove(Sender: TObject; Shift: TShiftState; X,
      Y: Integer);
    begin
      // If they move over the button, consider current CTRL key state
      if ssCtrl in Shift then
      begin
        Button1.Cursor := crSizeAll;
      end
      else
      begin
        Button1.Cursor := crDefault;
      end;
    end;
    

提交回复
热议问题