我制作了一个可垂直滚动的面板,我想让它可以水平滚动。我的代码通过使用鼠标或使用鼠标滚轮拖动它来使面板可滚动。
这是我的代码:
private Point _mouseLastPosition;
protected override void OnMouseDown(MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
_mouseLastPosition = e.Location;
}
base.OnMouseDown(e);
}
private int ValidateChange(int change)
{
var padding = -1;
if (change < 0)
{
var max = (from Control control in Controls select control.Left + control.Width + padding).Concat(new[] { int.MinValue }).Max();
if (max < Width + Math.Abs(change))
{
return Width - max;
}
}
else
{
var min = (from Control control in Controls select control.Left).Concat(new[] { int.MaxValue }).Min();
if (min > padding - Math.Abs(change))
{
return padding - min;
}
}
return change;
}
private void HandleDelta(int delta)
{
var change = ValidateChange(delta);
foreach (Control control in Controls)
{
control.Left += change;
}
}
protected override void OnMouseMove(MouseEventArgs e)
{
if ((MouseButtons & MouseButtons.Left) != 0)
{
var delta = _mouseLastPosition.X - e.X;
HandleDelta(delta);
_mouseLastPosition = e.Location;
}
base.OnMouseMove(e);
}
protected override void OnMouseWheel(MouseEventArgs e)
{
HandleDelta(e.Delta);
base.OnMouseWheel(e);
}
我需要更改哪些内容才能使其按照我希望的方式运行?
更新:我按照你告诉我的方式更改了我的代码,但它并没有像我想要的那样工作。这就是它现在的样子(我想让它向右滚动)。
答案 0 :(得分:0)
更改以下内容......
control.Top - &gt;&gt; control.Left
control.Height-&GT;&GT; control.Width
高度 - &GT;&GT; 宽度
var delta = e.Y - _mouseLastPosition.Y; - &GT;&GT; var delta = _mouseLastPosition.X - e.X;
<强>更新强>
这不是最佳解决方案,但您可以尝试一下吗?
保持初始状态..
private Dictionary<string, int> dicControls;
private bool isOverFlow;
protected override void InitLayout()
{
base.InitLayout();
if (dicControls == null)
{
dicControls = new Dictionary<string, int>();
foreach (Control control in Controls)
{
dicControls.Add(control.Name, control.Left);
}
var max = (from Control control in Controls select control.Left + control.Width + -1).Concat(new[] { int.MinValue }).Max();
isOverFlow = (Width - max) < 0;
}
}
private void HandleDelta(int delta)
{
var change = ValidateChange(delta);
foreach (Control control in Controls)
{
var initalLeft = dicControls[control.Name];
var tempLeft = control.Left + change;
if(isOverFlow)
{
if (tempLeft > initalLeft || delta > 0)
{
control.Left = initalLeft;
}
else
{
control.Left += change;
}
}
else
{
if (tempLeft < initalLeft)
{
control.Left = initalLeft;
}
else
{
control.Left += change;
}
}
}
}