从鼠标滚轮捕获垂直和水平滚动

时间:2014-09-12 19:51:18

标签: delphi winapi mouseevent delphi-xe2

我需要在我的应用程序中捕获鼠标滚轮事件,以便像现代UI一样移动视图区域,因为我的应用程序主要在笔记本电脑上运行。

我查看了Windows消息,显然只有从TWinControl继承的控件才能接收到鼠标消息。

我正在使用TApplicationEvents,它也可以捕获这些信息。我尝试处理WM_MOUSEWHEEL消息,但它仅适用于垂直滚动。我也尝试过处理WM_HSCROLLWM_HSCROLLCLIPBOARD消息,但根本没有捕获它们。

如何捕获垂直和特别水平的鼠标滚轮消息并在我的软件中使用它们?

2 个答案:

答案 0 :(得分:4)

您只需回复WM_MOUSEHWHEEL条消息即可。例如,这是我的一个类的摘录,它将水平鼠标滚轮滚动添加到滚动框中:

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;

答案 1 :(得分:0)

首先,你需要处理消息 WM_MOUSEHWHEEL

请注意字母“H”在那里( WM_MOUSE H WHEEL )。

我添加了TApplicationEvent组件并添加了以下代码 到OnMessage事件:

uses VCL.Controls;

.....

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
  var ctrl: TWinControl;
begin
  ctrl := FindVCLWindow(Mouse.CursorPos); //first I need to find the control under the mouse

  if ctrl is T3DWorldViewerComponent then //then I need to make sure
                                          //that the control under the mouse
                                          //is the 3D World Viewer contains my graphics

    if msg.message = WM_MOUSEHWHEEL then //then I need to make sure that I want to scroll Horizontally
    begin
      if msg.wParam=4287102976 then //this indicates that I'm scrolling to the left
        world.CameraMoveTo(MyCamera.Position.X+0.03, MyCamera.Position.Y, MyCamera.Position.Z)
      else
      if msg.wParam=7864320 then //and this indicates that I'm scrolling to the right
        world.CameraMoveTo(MyCamera.Position.X-0.03, MyCamera.Position.Y, MyCamera.Position.Z);
  end;
end;

完成!