加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 在textbox_textchanged上执行延迟

发布时间:2020-12-16 00:24:45 所属栏目:百科 来源:网络整理
导读:我有一个模拟键盘输入的条形码扫描仪.我用它在一个文本框中输入ISBN号,然后搜索该标题.我需要文本框方法在做任何事情之前等待10或13个字符的条目,但是我不知道如何去做. 到目前为止,我有以下内容: private void scanBox_TextChanged(object sender,EventArg
我有一个模拟键盘输入的条形码扫描仪.我用它在一个文本框中输入ISBN号,然后搜索该标题.我需要文本框方法在做任何事情之前等待10或13个字符的条目,但是我不知道如何去做.

到目前为止,我有以下内容:

private void scanBox_TextChanged(object sender,EventArgs e)
        {

            if (scanBox.Text.Length == 10)
            {
                getRecord10();
            }
            else if (scanBox.Text.Length == 13)
            {
                getRecord13();
            }
            else
            {
                MessageBox.Show("Not in directory","Error");
            }
        }

我正在考虑某种计时器实现来阻止最后一个条件,但我真正需要的是该方法等待10或13位数.条形码扫描器模拟按下的各个键,这就是它当前失败的原因.

解决方法

您可以在WPF中使用Timer(或DispatcherTimer).此示例应用程序在最后一次击键后300ms更新窗口标题.

System.Windows.Forms.Timer _typingTimer; // WinForms
    // System.Windows.Threading.DispatcherTimer _typingTimer; // WPF

    public MainWindow()
    {
        InitializeComponent();
    }

    private void scanBox_TextChanged(object sender,EventArgs e)
    {
        if (_typingTimer == null)
        {
            /* WinForms: */
            _typingTimer = new Timer();
            _typingTimer.Interval = 300;
            /* WPF: 
            _typingTimer = new DispatcherTimer();
            _typingTimer.Interval = TimeSpan.FromMilliseconds(300);
            */

            _typingTimer.Tick += new EventHandler(this.handleTypingTimerTimeout);
        }
        _typingTimer.Stop(); // Resets the timer
        _typingTimer.Tag = (sender as TextBox).Text; // This should be done with EventArgs
        _typingTimer.Start(); 
    }

    private void handleTypingTimerTimeout(object sender,EventArgs e)
    {
        var timer = sender as Timer; // WinForms
        // var timer = sender as DispatcherTimer; // WPF
        if (timer == null)
        {
            return;
        }

        // Testing - updates window title
        var isbn = timer.Tag.ToString();
        windowFrame.Text = isbn; // WinForms
        // windowFrame.Title = isbn; // WPF

        // The timer must be stopped! We want to act only once per keystroke.
        timer.Stop();
    }

部分代码取自Roslyn语法可视化工具

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读