考虑以下代码,我有一个文本 block ,它是 WPF 中的“开/关”按钮。它只是一个椭圆内的文本,上面写着开/关。当用户单击按钮并按住鼠标左键一秒钟时,如果设备尚未通电,它将执行“打开设备”代码。如果用户按住开/关按钮三秒钟或更长时间(按住鼠标左键),设备将关闭。
我错过了船上的几个问题。 1. 尽管计时器已启动,但按住鼠标按钮时不会触发 tick 事件。 2. 尽管抬起按钮,do/while 循环永远不会退出
谢谢!
public int TimerCount = 0;
private void ButtonPressTimer(object sender, EventArgs e)
{
TimerCount = TimerCount + 1;
}
private void txtBlockOnOff_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var buttonPressTimer = new DispatcherTimer(new TimeSpan(0, 0, 0, 1), DispatcherPriority.Normal, ButtonPressTimer, this.Dispatcher);
do
{
if (!buttonPressTimer.IsEnabled)
buttonPressTimer.Start();
}
while (e.ButtonState == MouseButtonState.Pressed);
buttonPressTimer.Stop();
if (TimerCount >= 3)
{
//do something here
}
else
{
//do something different here
}
}
最佳答案
我会考虑一种稍微不同的方法,它不需要设置计时器的开销。如果同时处理鼠标按下和向上事件,并存储按下按钮的时间,则可以将其与松开鼠标的时间进行比较并决定要做什么。
private DateTime mousePressed;
private void txtBlockOnOff_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
mousePressed = DateTime.Now;
}
private void txtBlockOnOff_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
// button released
TimeSpan difference = DateTime.Now - mousePressed;
if (difference.TotalSeconds >= 3)
{
// long press
}
else
{
// short press
}
}
关于c# - WPF DispatcherTimer 和鼠标按钮单击计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/948334/