我的表单中有各种按钮,每个按钮按下一个动作与之相关联。我想测量按钮被按下和释放之间的时间(以毫秒为单位)。我怎样才能为每个按钮做到这一点。
问问题
3463 次
3 回答
7
在 Form_Load 事件中,您可以迭代所有按钮并将 Stopwatch 动态附加到每个按钮,然后处理它们的 MouseDown 和 MouseUp 事件:
this.Controls.OfType<Button>().ToList().ForEach(button =>
{
button.Tag = new Stopwatch();
button.MouseDown += new MouseEventHandler(button_MouseDown);
button.MouseUp += new MouseEventHandler(button_MouseUp);
});
和功能:
void button_MouseUp(object sender, MouseEventArgs e)
{
Stopwatch watch = ((sender as Button).Tag as Stopwatch);
watch.Stop();
MessageBox.Show("This button was clicked for " + watch.Elapsed.TotalMilliseconds + " milliseconds");
watch.Reset();
}
void button_MouseDown(object sender, MouseEventArgs e)
{
((sender as Button).Tag as Stopwatch).Start();
}
于 2012-12-18T12:03:09.470 回答
2
可以使用StopWatch测量时间跨度,或使用性能分析器,如
Equatec,它也有一个免费选项。
于 2012-12-18T11:59:21.250 回答
1
您需要捕获down 事件的 andKeyDown
和up事件的 and。MouseDown
KeyUp
MouseUp
public Form1()
{
InitializeComponent();
button1.KeyDown += new KeyEventHandler(button1_down);
button1.MouseDown+=new MouseEventHandler(button1_down);
button1.KeyUp += new KeyEventHandler(button1_Up);
button1.MouseUp += new MouseEventHandler(button1_Up);
}
void button1_down(object sender, EventArgs e)
{
Console.WriteLine(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
}
private void button1_Up(object sender, EventArgs e)
{
Console.WriteLine(DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond);
}
于 2012-12-18T12:04:42.277 回答