Search code examples
delphiwinapimouseeventdelphi-xe2

Capturing vertical and horizontal scroll from mousewheel


I need to capture mousewheel events in my application to move the view area like modern UI's since my application will run mostly on laptops.

I have looked into Windows messages and apparently only controls inherited from TWinControl can recieve mousewheel messages.

I'm using TApplicationEvents, that can also capture those mesagges. I tried handling the WM_MOUSEWHEEL message, but it works only for vertical scrolling. I also tried handling WM_HSCROLL and WM_HSCROLLCLIPBOARD messages, but they were not captured at all.

How can I capture both vertical and especially horizontal mousewheel messages and use them in my software?


Solution

  • You simply need to respond to WM_MOUSEHWHEEL messages. For instance, here's an extract from a class of mine which adds horizontal mouse wheel scrolling to a scroll box:

    procedure TMyScrollBox.WndProc(var Message: TMessage);
    begin
      if Message.Msg=WM_MOUSEHWHEEL then begin
        (* For some reason using a message handler for WM_MOUSEHWHEEL doesn't work.
           The messages don't always arrive. It seems to occur when both scroll bars 
           are active. Strangely, if we handle the message here, then the messages 
           all get through. Go figure! *)
        if TWMMouseWheel(Message).Keys=0 then begin
          HorzScrollBar.Position := HorzScrollBar.Position 
            + TWMMouseWheel(Message).WheelDelta;
          Message.Result := 0;
        end else begin
          Message.Result := 1;
        end;
      end else begin
        inherited;
      end;
    end;