【问题标题】:TScrollbox scrolling using mouse wheel in c++ builder在 C++ builder 中使用鼠标滚轮滚动 TScrollbox
【发布时间】:2015-12-26 16:11:47
【问题描述】:

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

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;
}

但是当我尝试调试它时,滚动并没有发生,控制也没有出现。如何在滚动框中使用鼠标滚轮进行滚动?

【问题讨论】:

  • 你需要处理WM_MOUSEWHEEL消息,检查目标窗口是否为Scrollbox1并为其执行滚动

标签: delphi c++builder


【解决方案1】:

你可以在所有者窗体上实现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 组件并实现一个 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

【讨论】:

  • 我在滚动框内使用了 TStringGrid 组件,只有当我移动到该选项卡时,焦点才在字符串研磨上。这就是我认为滚动框的鼠标滚轮事件不起作用的原因。我不知道。然后我使用主窗体鼠标滚轮上下事件并检查活动选项卡是否是包含滚动框的工作表并执行滚动。现在工作正常。
  • 我在测试时只是在滚动框上放了一些按钮
  • 我通过在单击时将焦点设置为滚动框,将焦点从字符串网格更改为滚动框,我尝试上下滚动框鼠标滚轮。它现在也工作正常。
猜你喜欢
  • 1970-01-01
  • 2015-04-28
  • 2013-10-21
  • 2011-09-29
  • 1970-01-01
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 2012-06-07
相关资源
最近更新 更多