首页 > 解决方案 > 如何更改 C# 表单中的标签文本

问题描述

我有一个应用程序,可以将标签文本更改为使用条形码扫描仪扫描的序列号。代码一直有效,直到我的表单上有按钮。

我试过(1)关注标签,(2)创建一个组框并将标签放在组框中并专注于它,同时使用标签顺序和这个:

 this.ActiveControl = groupBox2;

两者都不起作用。

这是概述应用程序的代码:

 private void Form1_Load(object sender, EventArgs e)
    {
        this.ActiveControl = groupBox2;

        this.KeyDown += new KeyEventHandler(Form1_KeyDown);
        this.KeyUp += new KeyEventHandler(Form1_KeyUp);
    }

    private void Form1_KeyUp(object sender, KeyEventArgs e)
    {
        // if keyboard input is allowed to read
        if (UseKeyboard && e.KeyData != Keys.Enter)
        {
            MessageBox.Show(e.KeyData.ToString());
        }

        /* check if keydown and keyup is not different
         * and keydown event is not fired again before the keyup event fired for the same key
         * and keydown is not null
         * Barcode never fired keydown event more than 1 time before the same key fired keyup event
         * Barcode generally finishes all events (like keydown > keypress > keyup) of single key at a time, if two different keys are pressed then it is with keyboard
         */
        if (cforKeyDown != (char)e.KeyCode || cforKeyDown == '\0')
        {
            cforKeyDown = '\0';
            _barcode.Clear();
            return;
        }

        // getting the time difference between 2 keys
        int elapsed = (DateTime.Now.Millisecond - _lastKeystroke);

        /*
         * Barcode scanner usually takes less than 17 milliseconds to read, increase this if neccessary of your barcode scanner is slower
         * also assuming human can not type faster than 17 milliseconds
         */
        if (elapsed > 17)
            _barcode.Clear();

        // Do not push in array if Enter/Return is pressed, since it is not any Character that need to be read
        if (e.KeyCode != Keys.Return)
        {
            _barcode.Add((char)e.KeyData);
        }

        // Barcode scanner hits Enter/Return after reading barcode
        if (e.KeyCode == Keys.Return && _barcode.Count > 0)
        {
            string BarCodeData = new String(_barcode.ToArray());
            if (!UseKeyboard)
                //MessageBox.Show(String.Format("{0}", BarCodeData));
                label1.Text = String.Format("{0}", BarCodeData);
            _barcode.Clear();
        }

        // update the last key press strock time
        _lastKeystroke = DateTime.Now.Millisecond;
    }

再次,只要我拿出按钮,它就会起作用。这是我的用户界面的图片:

在此处输入图像描述

再次,标签更改,直到我开始向 WinForm 添加按钮。查看 UI,当用户扫描条形码时,“请扫描序列...”的行应该会改变。

标签: c#labeltextchanged

解决方案


推荐阅读