【问题标题】:Button long click [duplicate]按钮长按[重复]
【发布时间】:2020-10-26 12:39:24
【问题描述】:

我有一个用 c# 和 WinForms 开发的计时器,由外部按钮控制 当我按下按钮时,时间开始,这是主要动作!我想知道 是否可以识别长按此按钮,以便我可以将动作编程为停止 我对 C# 很陌生,通过编程语言方面是否可以识别这个长按?

【问题讨论】:

  • 向我们展示一些启动或停止计时器的代码会非常有帮助。关于您的问题,您可以使用按钮的 MouseDownMouseUp 事件。
  • 我一直在阅读这方面的内容,在我看来,这只是当我使用鼠标单击按钮时,对吗????我的计时器由连接到 PC 的外部按钮控制。这还能用吗?
  • 不知道你从这个外部按钮的界面得到什么信号是不可能的,但它是否提供了类似KeyUpKeyDown 从普通键盘获得的事件?
  • 我会说它是一样的,但如果这就是你的意思,我不会使用键盘上的任何键或鼠标本身。这个外部按钮通过开发按钮设备的公司提供的 DLL 与接口通信

标签: c# winforms stopwatch


【解决方案1】:

我的解决方案:

创建一个公共日期时间变量并将 button_mousedown 和 button_mouseup 事件添加到您的表单中。

将以下代码放入其中:

    private void button1_MouseDown(object sender, MouseEventArgs e)
    {
        dt = DateTime.Now;
    }

    private void button1_MouseUp(object sender, MouseEventArgs e)
    {
        var diff= ( DateTime.Now-dt).TotalMilliseconds;
        
        if(diff > x) // x is the minimum time you want the mouse to be down on the button
        {
            // do stuff
        }
    }

当您单击按钮时,准确时间存储在“dt”变量中。 单击结束时,将触发 mouseup 事件,您可以将按下按钮的时间与当前时间进行比较,您可以通过我的代码获得毫秒差异

【讨论】:

    【解决方案2】:

    您可以使用按钮 MouseDownMouseUp 事件。
    这是使用“长按”事件创建带有文本框和按钮的计数器的一种方法:

    private bool IsTargetButtonClicked = false;
    private Timer HoldButtonTimer;
    private void TargerButton_MouseUp(object sender, MouseEventArgs e)
    {
        IsTargetButtonClicked = false;
    }
    
    private void TargerButton_MouseDown(object sender, MouseEventArgs e)
    {
        IsTargetButtonClicked = true;
        InitHoldButtonTimer();
    }
    
    
    private void InitHoldButtonTimer()
    {           
        if (HoldButtonTimer == null)
        {
            HoldButtonTimer = new Timer();
            HoldButtonTimer.Interval = 100;
            HoldButtonTimer.Tick += HoldButtonTimer_Tick;
        }
    
        HoldButtonTimer.Start();           
    }
    
    
    private int SomeIntValueToAdvance = 0;
    private void HoldButtonTimer_Tick(object sender, EventArgs e)
    {
        if (IsTargetButtonClicked)
        {
            SomeIntValueToAdvance++;
    
            textBox1.Invoke(new Action(() =>
            {
                textBox1.Text = SomeIntValueToAdvance.ToString();
            }));
        }
        else
        {
            KillHoldButtonTimer();
        }
    }
    
    private void KillHoldButtonTimer()
    {           
        if (HoldButtonTimer == null)
        {
            HoldButtonTimer.Tick -= HoldButtonTimer_Tick;
            HoldButtonTimer.Stop();
            HoldButtonTimer.Dispose();
        }
    }
    

    输出:

    【讨论】:

    • 这真的很有帮助,但我不会使用键盘或鼠标上的任何键。它是连接到设备的外部按钮,并且设备连接到 PC。我的程序通过 DLL 与该设备通信。这还能用吗?
    • 是实现这个效果的原理,我不知道你的DLL有什么事件,但可能有类似行为的事件,但我不知道设备是什么,它是什么事件。
    猜你喜欢
    • 2018-01-11
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-29
    • 2021-01-30
    相关资源
    最近更新 更多