c# – 如何使用鼠标保持和释放检查TrackBar滑动
发布时间:2020-12-16 01:43:17 所属栏目:百科 来源:网络整理
导读:我的WinForms程序中有一个跟踪栏,通过移动它可以刷新一个庞大而耗时的方法.看看这段代码: trackBar_ValueChanged(object sender,EventArgs e){ this.RefreshData();} 这条轨道酒吧有20个台阶.如果用户抓住轨迹栏的滑块并在我的情况下从20拉到0,“刷新数据”
我的WinForms程序中有一个跟踪栏,通过移动它可以刷新一个庞大而耗时的方法.看看这段代码:
trackBar_ValueChanged(object sender,EventArgs e) { this.RefreshData(); } 这条轨道酒吧有20个台阶.如果用户抓住轨迹栏的滑块并在我的情况下从20拉到0,“刷新数据”将执行20次,虽然它在结束“刷新数据”值为0的过程时显示正确的数据,我想做类似的事情它仅在trackBar滑块释放时调用’RefreshData’,因此它不会处理轨迹栏上释放点的所有步骤. 任何有关实现这一目标的帮助和提示都将得到满足! 解决方法
我之前做过这种事情的方式是使用计时器.每次TrackBar的值发生变化时,重置计时器,使其在500毫秒(或适合您的任何情况下)触发.如果用户在计时器触发之前更改了值,它将再次重置,这意味着即使它多次更改,计时器也只会触发一次.
这里唯一要注意的是计时器将在另一个线程上触发,你将无法从该线程更新UI,因此你必须重新调用UI线程来进行更改.但是,如果您可以将大部分昂贵的工作转移到此后台线程上,那么您将保持UI的响应时间更长. 这里有一些示例代码,可以让您了解我的意思. public partial class Form1 : Form { private int updateCount; private System.Threading.Timer timer; public Form1() { this.InitializeComponent(); this.timer = new System.Threading.Timer(this.UpdateValue); } private void UpdateValue(object state) { // Prevent the user from changing the value while we're doing // our expensive operation this.Invoke(new MethodInvoker(() => this.trackBar1.Enabled = false)); // Do the expensive updates - this is still on a background thread this.updateCount++; this.Invoke(new MethodInvoker(this.UpdateUI)); } private void UpdateUI() { this.label1.Text = this.updateCount.ToString(); // Re-enable the track bar again this.trackBar1.Enabled = true; } private void trackBar1_ValueChanged(object sender,EventArgs e) { this.timer.Change(TimeSpan.FromMilliseconds(500),new TimeSpan(-1)); } } 编辑:这是一个使用win forms计时器来执行计时的解决方案.这里的不同之处在于,您将在计算运行时锁定UI;在您的情况下,这可能会或可能不会. public partial class Form1 : Form { private int updateCount; private Timer timer; public Form1() { this.InitializeComponent(); this.timer = new Timer(); this.timer.Interval = 500; this.timer.Tick += this.Timer_Tick; } private void Timer_Tick(object sender,EventArgs e) { this.timer.Stop(); this.updateCount++; this.label1.Text = this.updateCount.ToString(); } private void trackBar1_ValueChanged(object sender,EventArgs e) { this.timer.Stop(); this.timer.Start(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |