gpt4 book ai didi

c# - 如何使用鼠标滚轮让 DataGridView 一次滚动一项?

转载 作者:太空狗 更新时间:2023-10-29 20:22:42 29 4
gpt4 key购买 nike

我们希望在通过此控件使用鼠标滚轮时覆盖 DataGridView 的默认行为。默认情况下,DataGridView 滚动的行数等于 SystemInformation.MouseWheelScrollLines 设置。我们想要做的是一次只滚动一个项目。

(我们在 DataGridView 中显示图像,这些图像有点大。由于这种滚动三行(典型的系统设置)太多,经常导致用户滚动到他们甚至看不到的项目。)

我已经尝试了几件事,但到目前为止还没有取得太大的成功。以下是我遇到的一些问题:

  1. 您可以订阅 MouseWheel 事件,但无法将事件标记为已处理并执行我自己的操作。

  2. 您可以覆盖 OnMouseWheel 但这似乎从未被调用。

  3. 您或许可以在基本滚动代码中更正此问题,但这听起来像是一项困惑的工作,因为其他类型的滚动(例如使用键盘)来自相同的管道。

谁有好的建议?

这是最终代码,使用给出的精彩答案:

    /// <summary>
/// Handle the mouse wheel manually due to the fact that we display
/// images, which don't work well when you scroll by more than one
/// item at a time.
/// </summary>
///
/// <param name="sender">
/// sender
/// </param>
/// <param name="e">
/// the mouse event
/// </param>
private void mImageDataGrid_MouseWheel(object sender, MouseEventArgs e)
{
// Hack alert! Through reflection, we know that the passed
// in event argument is actually a handled mouse event argument,
// allowing us to handle this event ourselves.
// See http://tinyurl.com/54o7lc for more info.
HandledMouseEventArgs handledE = (HandledMouseEventArgs) e;
handledE.Handled = true;

// Do the scrolling manually. Move just one row at a time.
int rowIndex = mImageDataGrid.FirstDisplayedScrollingRowIndex;
mImageDataGrid.FirstDisplayedScrollingRowIndex =
e.Delta < 0 ?
Math.Min(rowIndex + 1, mImageDataGrid.RowCount - 1):
Math.Max(rowIndex - 1, 0);
}

最佳答案

我自己做了一些搜索和测试。我用了Reflector调查并发现了一些事情。 MouseWheel 事件提供了一个 MouseEventArgs 参数,但是 DataGridView 中的 OnMouseWheel() 覆盖将其转换为 已处理MouseEventArgs。这在处理 MouseWheel 事件时也有效。 OnMouseWheel() 确实被调用了,它在 DataGridView 的覆盖中使用了 SystemInformation.MouseWheelScrollLines

所以:

  1. 您确实可以处理 MouseWheel 事件,将 MouseEventArgs 转换为 HandledMouseEventArgs 并设置 Handled = true,然后做你想做的。

  2. 子类 DataGridView,自己覆盖 OnMouseWheel(),并尝试重新创建我在 Reflector 中阅读的所有代码除了将 SystemInformation.MouseWheelScrollLines 替换为 1

后者将是一个巨大的痛苦,因为它使用了许多私有(private)变量(包括对 ScrollBar 的引用)并且您必须用自己的变量替换一些并使用反射获取/设置其他变量.

关于c# - 如何使用鼠标滚轮让 DataGridView 一次滚动一项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/135105/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com