【发布时间】:2021-07-17 12:15:53
【问题描述】:
请告诉我如何找出面板的内部尺寸 (MAX) 以便滚动到正确的位置。
截图中的数字是“随机生成的”,代码和项目描述了一切。
获取最后一个内部元素的坐标时,结果值比用于获取该元素的值小很多倍。
public Form_Main() {
InitializeComponent();
flp_Elements.MouseWheel += Flp_Els_MouseWheel;
}
// Scrolling the panel (Flp_Els) with the mouse wheel
private void Flp_Els_MouseWheel(object sender, MouseEventArgs e) {
int step = customScrollBar1.Value -= e.Delta > 0 ? customScrollBar1.SmallStep : -customScrollBar1.SmallStep;
customScrollBar1.Value = Math.Max(customScrollBar1.Minimum, Math.Min(step, customScrollBar1.Maximum));
ScrollValue = (int)customScrollBar1.Value;
}
// Scroll the panel (Flp_Els) with the slider on the ScrollBar
private void customScrollBar1_ValueChanged(object sender, EventArgs e) {
ScrollValue = customScrollBar1.Value;
}
// Method for overriding the maximum value, when adding elements to the panel
private void flp_Elements_ControlAdded(object sender, ControlEventArgs e) {
// it managed to scroll beyond (3820) max - it does not move further,
// but the number of max is greater than above
// ! HOW TO DETERMINE THE SIZES OF THE PANEL, WHEN IT IS FILLED WITH ELEMENTS AND HIDES THEM
customScrollBar1.Maximum = flp_Elements.VerticalScroll.Maximum + flp_Elements.VerticalScroll.LargeChange * 8;
flp_Elements.VerticalScroll.Maximum = customScrollBar1.Maximum;
}
// WITHOUT IT, THE CONTENT OF THE PANEL WOULD NOT MOVE
// Setting panel limits
public int scrollValue = 0;
public int ScrollValue {
get { return scrollValue; }
set {
scrollValue = value;
// Minimum = 0
if (scrollValue < 0) scrollValue = 0;
// Maximum
if (scrollValue > flp_Elements.VerticalScroll.Maximum)
scrollValue = flp_Elements.VerticalScroll.Maximum;
flp_Elements.VerticalScroll.Value = scrollValue;
}
}
}
目前:面板使用 ScrollBar 滚动,但为了让一切正常工作,您需要这个数字。尝试了不同的选项,但它们不能按需要工作:
【问题讨论】:
-
当 ScrollableControl 包含位于 DisplayRectangle 之外的子控件时,其大小由
Control.PreferredSize返回。您的最小滚动值始终为 0,real 最大值始终考虑ScrollableControl.ClientSize,需要从最大值中减去(与水平或垂直滚动条相关的维度)。 -
你能写一段代码来描述你想说的话吗?
-
要编写一段代码,我需要写下整个 ScrollBar 自定义控件。滚动条与承载它的控件协作,以发送/接收与客户区位置、调整大小事件、鼠标事件等相关的消息。 - 您当前正在计算滚动条而不考虑承载滚动条的控件的 ClientSize(它就是在这种情况下,看起来 Scrollbar 不是 ScrollableControl 的子控件)。如前所述,实际的最大滚动值为,例如,
ScrollBar.Maximum (= Control.PreferredSize.Height) - Control.ClientSize.Height。 -
为了测试这个行为,构建一个自定义控件继承,例如,面板类。覆盖 WndProc 并处理
WM_MOUSEHWHEEL、WM_VSCROLL和WM_HSCROLL(至少)。打印VerticalScroll.Value、VerticalScroll.Maximum、VerticalScroll.Maximum - ClientSize.Height、HorizontalScroll.Maximum - ClientSize.Width、PreferredSize和ClientSize的值。所以你可以看到是什么。 -
试试this。将
pnlInner替换为您的flp_Elements控件。
标签: c# windows visual-studio winforms