将滚动事件发送到表单

时间:2016-08-29 10:13:54

标签: c# winforms scrollbar richtextbox

在我的Windows窗体应用程序中,经常出现用户滚动面板然后被richtextbox阻止的情况。我想抓住滚动事件,并在richtextbox垂直滚动条不可见时将其发送到面板。

我已找到代码来检查此线程中是否显示垂直滚动条:https://social.msdn.microsoft.com/Forums/en-US/a3facad3-0eae-4610-9a63-1b6c7a718bf5/how-do-you-determine-if-vertical-scroll-bar-is-visible-in-richtextbox?forum=winforms

VScroll事件的richtextbox事件仅在verticalscrollbar已经可见时触发。

捕获mousescroll并将其发送到正确的面板的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

我认为你可以在Form1.Designer.cs中的富文本框中添加一个事件,如下代码:

this.richTextBox1.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.richTextBox1_MouseWheel);

并将此功能添加到表单中:

private void richTextBox1_MouseWheel(object sender, MouseEventArgs e)
{
    Control control = sender as Control;
    if (!NativeMethods.VerticalScrollBarVisible(control))
    {
        int numberOfTextLinesToMove = e.Delta * SystemInformation.MouseWheelScrollLines;
        int numberOfPixelsToMove = numberOfTextLinesToMove * Convert.ToInt32(control.Font.Size);
        if (panel1.VerticalScroll.Value - numberOfPixelsToMove < panel1.VerticalScroll.Minimum)
            panel1.VerticalScroll.Value = panel1.VerticalScroll.Minimum;
        else if (panel1.VerticalScroll.Value - numberOfPixelsToMove > panel1.VerticalScroll.Maximum)
            panel1.VerticalScroll.Value = panel1.VerticalScroll.Maximum;
        else
            panel1.VerticalScroll.Value -= numberOfPixelsToMove;
    }
}

VerticalScrollBarVisible方法在this MSDN thread中解释。

答案 1 :(得分:0)

当垂直滚动条不可见时,@ Farshad建议的事件MouseWheel也会触发。然后我添加了以下代码来滚动panel1。请注意,MouseWheel事件未在visual studio designer中显示,必须手动添加到Form.Designer.cs。

private void richTextBox1_MouseWheel(object sender, MouseEventArgs e)
{
    Control control = sender as Control;
    if (!VerticalScrollBarVisible(control))
    {
        int numberOfTextLinesToMove = e.Delta * SystemInformation.MouseWheelScrollLines;
        int numberOfPixelsToMove = numberOfTextLinesToMove * Convert.ToInt32(control.Font.Size);
        if (panel1.VerticalScroll.Value - numberOfPixelsToMove < panel1.VerticalScroll.Minimum)
            panel1.VerticalScroll.Value = panel1.VerticalScroll.Minimum;
        else if (panel1.VerticalScroll.Value - numberOfPixelsToMove > panel1.VerticalScroll.Maximum)
            panel1.VerticalScroll.Value = panel1.VerticalScroll.Maximum;
        else
            panel1.VerticalScroll.Value -= numberOfPixelsToMove;
    }
}

[System.Runtime.InteropServices.DllImport("user32.dll")]
private extern static int GetWindowLong(IntPtr hWnd, int index);

public static bool VerticalScrollBarVisible(Control ctl) {
  int style = GetWindowLong(ctl.Handle, -16);
  return (style & 0x200000) != 0;
}