How to prevent focused control from scrolling when

2019-05-28 19:23发布

问题:

Refer to this prior related question. While the answers there do work, I have further issues when it comes to certain types of controls such as a TDBGrid. If the TDBGrid currently has focus, but the mouse is pointed over another control to scroll, the TDBGrid scrolls anyway, thus resulting in two different controls scrolling at the same time. This happens in every single solution which I've found so far related to scrolling the control underneath the mouse.

How can I prevent this behavior and ensure that only the control under the mouse scrolls, and nothing else?

回答1:

This code works fine for me.

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
var
  Control: TWinControl;
begin

  if Msg.message = WM_MOUSEWHEEL then
  begin
    // Find control at mouse cursor
    Control := FindVCLWindow(Msg.pt);

    if Assigned(Control) then
    begin
      // Try to scroll
      if Control.Perform(CM_MOUSEWHEEL, Msg.wParam, Msg.lParam) <> 0 then
        Handled := True
      else
      // If no scroll was performed by control,
      // then detrmine if message control is at mouse cursor.
      // If not, then supress message
      if Control.Handle <> Msg.hwnd then
        Handled := True;
    end;
  end;

end;