TScrollbox在c ++ builder中使用鼠标滚轮滚动

时间:2015-12-26 05:32:16

标签: delphi c++builder

我在表单的标签页中添加了一个滚动框。当我单击滚动框中的向上和向下滚动按钮时,我能够滚动内容。但我想用鼠标滚轮上下滚动内容。我试过以下代码。

void __fastcall TForm1::ScrollBox1MouseWheelUp(TObject *Sender, TShiftState Shift,
      TPoint &MousePos, bool &Handled)
{
    Form1->ScrollBox1->VertScrollBar->Position -= 3;
}

void __fastcall TForm1::ScrollBox1MouseWheelDown(TObject *Sender, TShiftState Shift,
      TPoint &MousePos, bool &Handled)
{
    Form1->ScrollBox1->VertScrollBar->Position += 3;
}

但滚动没有发生,当我试图调试它时控制不会在这里。如何在滚动框中使用鼠标滚轮滚动?

1 个答案:

答案 0 :(得分:2)

您可以在所有者表单上实现MouseWheel事件,然后在鼠标下测试Control是TScrollBox:

procedure TForm1.FormMouseWheel(Sender: TObject; Shift: TShiftState; WheelDelta: Integer; MousePos: TPoint; var Handled: Boolean);
var
  i: Integer;
  TheScrollBox: TScrollBox;
  Control: TWinControl;
begin
  Control := FindVCLWindow(Mouse.CursorPos);
  Handled := Control is TScrollBox;

  if not Handled then
    exit;

  TheScrollBox := Control as TScrollBox;

  for i := 1 to Mouse.WheelScrollLines do
    try
      if WheelDelta > 0 then
        TheScrollBox.Perform(WM_VSCROLL, SB_LINEUP, 0)
      else
        TheScrollBox.Perform(WM_VSCROLL, SB_LINEDOWN, 0);
    finally
      TheScrollBox.Perform(WM_VSCROLL, SB_ENDSCROLL, 0);
    end;
end;

另一种更通用的方法是实现Application.OnMessage:

将一个TApplicationEvents组件添加到mainform,并将实现添加到OnMessageEvent:

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG; var Handled: Boolean);
var
  i, Count: Integer;
  Control: TWinControl;
begin
  if Msg.message <> WM_MOUSEWHEEL then
    exit;

  Control := FindVCLWindow(Mouse.CursorPos);
  Handled := Control <> nil;

  if not Handled then
    exit;

  Count := 1;
  if Smallint(loWord(Msg.wParam)) = MK_CONTROL then
    Count := 5;

  try
    for i := 1 to Count do
      if Smallint(HiWord(Msg.wParam)) > 0 then
        Control.Perform(WM_VSCROLL, SB_LINEUP, 0)
      else
        Control.Perform(WM_VSCROLL, SB_LINEDOWN, 0);
  finally
    Control.Perform(WM_VSCROLL, SB_ENDSCROLL, 0);
  end;
end;

PS:WPARAM和LPARAM记录在MSDN