如何在按下键盘键时更改TrackBar控制动作
本文关键字:TrackBar 控制 键盘 | 更新日期: 2023-09-27 18:15:51
当TrackBar
控件被改变时,其方向与预期方向相反:向上/向下/向上/向下箭头
在这里详细提到:为什么Trackbar的值减少箭头向上/PgUp?
是否有办法修复/逆转这个行为?
嗯…我以前从没注意过。以下是我对@Hans的建议的尝试:
public class MyTrackBar : TrackBar
{
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
switch (keyData)
{
case Keys.Up:
this.Value = Math.Min(this.Value + this.SmallChange, this.Maximum);
return true;
case Keys.Down:
this.Value = Math.Max(this.Value - this.SmallChange, this.Minimum);
return true;
case Keys.PageUp:
this.Value = Math.Min(this.Value + this.LargeChange, this.Maximum);
return true;
case Keys.PageDown:
this.Value = Math.Max(this.Value - this.LargeChange, this.Minimum);
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
Idle_Mind的答案很好,实际上帮助了我,但它有一个缺点,即当Up, Down, PageUp或PageDown被点击时,它会阻止控件提高Scroll
和ValueChanged
事件。所以,这是我的版本:
public class ProperTrackBar : TrackBar
{
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
int oldValue = this.Value;
switch (keyData)
{
case Keys.Up:
this.Value = Math.Min(this.Value + this.SmallChange, this.Maximum);
break;
case Keys.Down:
this.Value = Math.Max(this.Value - this.SmallChange, this.Minimum);
break;
case Keys.PageUp:
this.Value = Math.Min(this.Value + this.LargeChange, this.Maximum);
break;
case Keys.PageDown:
this.Value = Math.Max(this.Value - this.LargeChange, this.Minimum);
break;
default:
return base.ProcessCmdKey(ref msg, keyData);
}
if (Value != oldValue)
{
OnScroll(EventArgs.Empty);
OnValueChanged(EventArgs.Empty);
}
return true;
}
}