c# - WPF DispatcherTimer 和鼠标按钮单击计时

标签 c# .net wpf

考虑以下代码,我有一个文本 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/

相关文章:

c# - 将 KeyValuePair<int,string> 转换为 int[] 数组和 string[] 数组

wpf - ContentControl 更改 GotFocus 上的 ContentTemplate

WPF 数据网格行水平对齐问题

c# - 在 C# 中将 Grid 的 IsMouseOver 设置为 True

c# - 如何从 Visual Studio 中手动终止特定(正在运行的)线程

c# - Asp.net MVC 5 - 查看将空数据发布到 Controller

c# - 一些帮助理解 "yield"

.NET - 从用作网络摄像机的 Windows 手机获取视频流

C# 字符串比较等于 false

c# - 基于服务的系统中 session (跟踪)ID 的设计模式?