我的表单中有各种按钮,按下每个按钮都会关闭一个动作。我想测量按下和释放按钮之间的时间(以毫秒为单位)。我如何为每个按钮执行此操作。
答案 0 :(得分:7)
在Form_Load事件中,您可以迭代所有按钮并动态地将秒表附加到每个按钮,然后处理它们的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();
}
答案 1 :(得分:2)
答案 2 :(得分:1)
您需要捕获向下事件的KeyDown
和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);
}