winforms 如何记录trackBar的最后一个值和当前值,找出不同之处,并将最后一个值和当前值之间的所有数字分配给标签?

nr9pn0ug  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(223)

包括上次值和当前值。当前代码不更改标签文本。
目标是无论我多快地向左或向右移动鼠标都能捕获trackBar值。
我尝试了鼠标上下移动事件,但效果不好。不知道如何计算这些事件。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Sliders
{
    public partial class Form1 : Form
    {
        Label[] tile = new Label[11];

        int oldValue = 0;
        int lastValue = 0;

        public Form1()
        {
            InitializeComponent();

            oldValue = macTrackBar1.Value;

            for (int i = 0; i < tile.Length; i++)
            {
                tile[i] = new Label();
                tile[i].Height = 18;
                tile[i].Width = 10;
                tile[i].Left = 0;
                tile[i].Top = i * 20;
                tile[i].Text = i.ToString();
                tile[i].Visible = true;
                Controls.Add(tile[i]);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void macTrackBar1_ValueChanged(object sender, decimal value)
        {
            if(lastValue > oldValue)
            {
                int newValue = lastValue - oldValue;

                for(int i = 0; i < newValue; i++)
                {
                    tile[i].Text = i.ToString();
                }
            }
        }

        private void macTrackBar1_MouseUp(object sender, MouseEventArgs e)
        {
            lastValue = macTrackBar1.Value;
        }

        private void macTrackBar1_MouseDown(object sender, MouseEventArgs e)
        {
            oldValue = macTrackBar1.Value;
        }
    }
}
v1uwarro

v1uwarro1#

您需要将lastValue = macTrackBar1.Value;放到macTrackBar1_ValueChanged事件中。其次,private void macTrackBar1_ValueChanged(object sender, decimal value)不是有效的事件处理程序,我认为您需要像private void macTrackBar1_ValueChanged(object sender, EventArgs e)那样使用它

private void macTrackBar1_ValueChanged(object sender, decimal value)
    {
        lastValue = macTrackBar1.Value;
        if(lastValue > oldValue)
        {
            
            int newValue = lastValue - oldValue;

            for(int i = 0; i < newValue; i++)
            {
                tile[i].Text = i.ToString();
            }
        }
    }

    private void macTrackBar1_MouseUp(object sender, MouseEventArgs e)
    {
        
    }

    private void macTrackBar1_MouseDown(object sender, MouseEventArgs e)
    {
        oldValue = macTrackBar1.Value;
    }

标签未更改,因为您将相同的文本放入其中。始终将相同的索引值放入其中。请尝试:

tile[i].Text = newValue.ToString();

相关问题