为什么在更改其中一个trackBars值时将手表的其他值重置为0?

时间:2018-10-09 16:31:29

标签: c# winforms

代码:

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;
using System.Diagnostics;
using System.IO;
using DannyGeneral;

namespace StopwatchTimer
{
    public partial class Form1 : Form
    {
        private static readonly Stopwatch watch = new Stopwatch();
        private long diff = 0, previousTicks = 0, ticksDisplayed = 0;
        private OptionsFile optionsfile = new OptionsFile(Path.GetDirectoryName(Application.LocalUserAppDataPath) + "\\Settings.txt");
        private string result;

        public Form1()
        {
            InitializeComponent();

            richTextBox1.TabStop = false;
            richTextBox1.ReadOnly = true;
            richTextBox1.BackColor = Color.White;
            richTextBox1.Cursor = Cursors.Arrow;
            richTextBox1.Enter += RichTextBox1_Enter;

            trackBarHours.Value = Convert.ToInt32(optionsfile.GetKey("trackbarhours"));
            trackBarMinutes.Value = Convert.ToInt32(optionsfile.GetKey("trackbarminutes"));
            trackBarSeconds.Value = Convert.ToInt32(optionsfile.GetKey("trackbarseconds"));

            richTextBox1.Text = optionsfile.GetKey("result");

            string radiobutton1 = optionsfile.GetKey("radiobutton1");
            bool b;
            bool.TryParse(radiobutton1.Trim(), out b);

            radioButton1.Checked = b;
            if (ticksDisplayed > 0 && b == false)
                radioButton2.Checked = true;

            if(trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0)
            {
                btnPause.Enabled = false;
                btnReset.Enabled = false;
            }
            else
            {
                btnPause.Enabled = false;
                btnReset.Enabled = true;
            }

            //UpdateTime();
        }

        private void RichTextBox1_Enter(object sender, EventArgs e)
        {
            btnStart.Focus();
        }

        private void UpdateTime()
        {
            if (ticksDisplayed > 0)
                btnReset.Enabled = true;

            richTextBox1.Text = GetTimeString(watch.Elapsed);
            optionsfile.SetKey("result", result.ToString());
        }

        private string GetTimeString(TimeSpan elapsed)
        {
            result = string.Empty;

            //calculate difference in ticks
            diff = elapsed.Ticks - previousTicks;

            if (radioButton1.Checked == true)
            { //counting up
                ticksDisplayed += diff;
            }
            else
            { //counting down
                ticksDisplayed -= diff;
            }

            if (ticksDisplayed < 0)
            {
                ticksDisplayed = 0;
            }

            //Make ticksDisplayed to regular time to display in richtextbox
            TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);

            result = string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
                ctimeSpan.Hours,
                ctimeSpan.Minutes,
                ctimeSpan.Seconds,
                ctimeSpan.Milliseconds);

            previousTicks = elapsed.Ticks;

            return result;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (btnStart.Text == "START")
            {
                watch.Reset();

                //Here
                TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
                diff = 0;
                previousTicks = 0;
                ticksDisplayed = ctimeSpan.Ticks;

                watch.Start();
                btnStart.Text = "STOP";
                btnPause.Enabled = true;
                btnReset.Enabled = true;
                timer1.Enabled = true;
            }
            else
            {
                watch.Stop();
                btnStart.Text = "START";
                btnPause.Text = "PAUSE";
                btnPause.Enabled = false;
                if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0 && ticksDisplayed == 0)
                {
                    btnReset.Enabled = false;
                }
                else
                {
                    btnReset.Enabled = true;
                }

                if (ticksDisplayed > 0)
                    btnReset.Enabled = true;
                    timer1.Enabled = false;
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            watch.Reset();

            if (btnStart.Text == "STOP")
                watch.Start();
            diff = 0;
            previousTicks = 0;
            ticksDisplayed = 0;
            trackBarHours.Value = 0;
            trackBarMinutes.Value = 0;
            trackBarSeconds.Value = 0;
            if (trackBarHours.Value == 0 && trackBarMinutes.Value == 0 && trackBarSeconds.Value == 0)
            {
                btnReset.Enabled = false;
            }
            else
            {
                btnReset.Enabled = true;
            }

            UpdateTime();
        }

        private void trackBarHours_Scroll(object sender, EventArgs e)
        {
            //get ticksDisplayed as TimeSpan
            TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
            //change only the hour
            TimeSpan htimeSpan = new TimeSpan(ctimeSpan.Days, trackBarHours.Value, ctimeSpan.Minutes, ctimeSpan.Seconds, ctimeSpan.Milliseconds);

            //set it to ticksDisplayed and update.
            ticksDisplayed = htimeSpan.Ticks;

            if (trackBarSeconds.Value == 0 && trackBarHours.Value == 0 && trackBarMinutes.Value == 0)
                btnStart.Enabled = false;

            if (trackBarHours.Value > 0)
            {
                btnStart.Enabled = true;
                btnReset.Enabled = true;
            }

            optionsfile.SetKey("trackbarhours", trackBarHours.Value.ToString());

            UpdateTime();
        }

        private void trackBarMinutes_Scroll(object sender, EventArgs e)
        {
            TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
            TimeSpan mtimeSpan = new TimeSpan(ctimeSpan.Days, ctimeSpan.Hours, trackBarMinutes.Value, ctimeSpan.Seconds, ctimeSpan.Milliseconds);

            ticksDisplayed = mtimeSpan.Ticks;

            if (trackBarSeconds.Value == 0 && trackBarHours.Value == 0 && trackBarMinutes.Value == 0)
                btnStart.Enabled = false;

            if (trackBarMinutes.Value > 0)
            {
                btnStart.Enabled = true;
                btnReset.Enabled = true;
            }

            optionsfile.SetKey("trackbarminutes", trackBarMinutes.Value.ToString());

            UpdateTime();
        }

        private void trackBarSeconds_Scroll(object sender, EventArgs e)
        {
            TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
            TimeSpan stimeSpan = new TimeSpan(ctimeSpan.Days, ctimeSpan.Hours, ctimeSpan.Minutes, trackBarSeconds.Value, ctimeSpan.Milliseconds);

            ticksDisplayed = stimeSpan.Ticks;

            if (trackBarSeconds.Value == 0 && trackBarHours.Value == 0 && trackBarMinutes.Value == 0)
                btnStart.Enabled = false;

            if (trackBarSeconds.Value > 0)
            {
                btnStart.Enabled = true;
                btnReset.Enabled = true;
            }

            optionsfile.SetKey("trackbarseconds", trackBarSeconds.Value.ToString());

            UpdateTime();
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            optionsfile.SetKey("radiobutton1", radioButton1.Checked.ToString());
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            if (btnStart.Text == "STOP")
            {
                if (btnPause.Text == "PAUSE")
                {
                    btnPause.Text = "CONTINUE";
                    watch.Stop();
                    timer1.Enabled = false;
                }
                else
                {
                    btnPause.Text = "PAUSE";
                    watch.Start();
                    timer1.Enabled = true;
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            UpdateTime();
        }
    }
}

例如,现在在运行应用程序并从保存的文本文件中加载值时,trackBars的值如下所示:小时= 1分钟= 10秒= 50

如果现在我将更改一个trackBars值,则richTextBox中的其他值将更改为00,其他两个trackBars将保持相同的值,但是riachTextBox中的两个trackBars的值将更改为00。

例如,我第一次在richTextBox中运行应用程序,时间是:01:10:50.000 trackBars值是相同的1 10 50现在我将小时数的小时TrackBar的值01更改为05两个trackBar将保持在值10和50,但在richTextBox中,将10和50重置为00:00。

不知道为什么。

这是用于保存/加载设置的类t =

/*----------------------------------------------------------------
 * Module Name  : OptionsFile
 * Description  : Saves and retrievs application options
 * Author       : Danny
 * Date         : 10/02/2010
 * Revision     : 1.00
 * --------------------------------------------------------------*/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Configuration;


/*
 *  Introduction :
 * 
 *  This module helps in saving application options
 * 
 * 
 *  Typical file could look like this:
 *  user_color=Red
 *  time_left=30
 *  
 * 
 * 
 * 
 * 
 * */

namespace DannyGeneral
{
    class OptionsFile
    {
        /*----------------------------------------
         *   P R I V A T E     V A R I A B L E S 
         * ---------------------------------------*/


        /*---------------------------------
         *   P U B L I C   M E T H O D S 
         * -------------------------------*/
        string path_exe;
        string temp_settings_file;
        string temp_settings_dir;
        string Options_File;
        StreamWriter sw;
        StreamReader sr;

        /*----------------------------------------------------------
         * Function     : OptionsFile
         * Description  : Constructor
         * Parameters   : file_name is the name of the file to use
         * Return       : none
         * --------------------------------------------------------*/

        ///<summary>
        ///<para>Enter a path with a filename</para>
        ///</summary>
        public OptionsFile(string settingsFileAndPath)
    {
        if (!File.Exists(settingsFileAndPath))
        {
            if (!Directory.Exists(Path.GetDirectoryName(settingsFileAndPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(settingsFileAndPath));
            }
            File.Create(settingsFileAndPath).Close();
        }
        path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
        Options_File = settingsFileAndPath; 
    }

/*----------------------------------------------------------
 * Function     : GetKey
 * Description  : gets the value of the key.
 * Parameters   : key
 * Return       : value of the key if key exist, null if not exist
 * --------------------------------------------------------*/
    public string GetKey(string key)
    {

      //  string value_of_each_key;
        string key_of_each_line;
        string line;
        int index;
        string key_value;
        key_value = null;

        sr = new StreamReader(Options_File);
        while (null != (line = sr.ReadLine()))
        {


            index = line.IndexOf("=");


           //    value_of_each_key = line.Substring(index+1);



            if (index >= 1)
            {
                key_of_each_line = line.Substring(0, index);
                if (key_of_each_line == key)
                {
                    key_value = line.Substring(key.Length + 1);
                }

            }
            else
            {
            }


        }
        sr.Close();
        return key_value;
    }


/*----------------------------------------------------------
 * Function     : SetKey
 * Description  : sets a value to the specified key
 * Parameters   : key and a value
 * Return       : none
 * --------------------------------------------------------*/
    public void SetKey(string key , string value)
    {
        bool key_was_found_inside_the_loop;
        string value_of_each_key;
        string key_of_each_line ;
        string line;
        int index;
        key_was_found_inside_the_loop = false;

        temp_settings_file = "\\temp_settings_file.txt";
        temp_settings_dir = path_exe + @"\temp_settings";
        if (!Directory.Exists(temp_settings_dir))
        {
            Directory.CreateDirectory(temp_settings_dir);
        }

        sw = new StreamWriter(temp_settings_dir+temp_settings_file);
        sr = new StreamReader(Options_File);
        while (null != (line = sr.ReadLine()))
        {

            index = line.IndexOf("=");
            key_of_each_line = line.Substring(0, index);
            value_of_each_key = line.Substring( index + 1);
         //   key_value = line.Substring(0,value.Length);
            if (key_of_each_line == key)
            {
                sw.WriteLine(key + "=" + value);
                key_was_found_inside_the_loop = true;

            }
            else
            {
               sw.WriteLine(key_of_each_line+"="+value_of_each_key);
            }

        }

        if (!key_was_found_inside_the_loop)
        {
            sw.WriteLine(key + "=" + value);
        }
        sr.Close();
        sw.Close();
        File.Delete(Options_File);
        File.Move(temp_settings_dir + temp_settings_file, Options_File);
        return;

    }



    public List<float> GetListFloatKey(string keys)
    {
        List<float> result = new List<float>();
        string s = GetKey(keys);
        if (s != null)
        {
            string[] items = s.Split(new char[] { ',' });
            float f;
            foreach (string item in items)
            {
                if (float.TryParse(item, out f))
                    result.Add(f);
            }
            return result;
        }
        else
        {
            return result;
        }
    }


    public void SetListFloatKey(string key, List<float> Values)
    {
        StringBuilder sb = new StringBuilder();
        foreach (float value in Values)
        {
            sb.AppendFormat(",{0}", value);
        }
        if (Values.Count == 0)
        {
            SetKey(key, "");
        }
        else
        {
            SetKey(key, sb.ToString().Substring(1));
        }
    }

    public List<int> GetListIntKey(string keys)
    {
        /*List<int> t = new List<int>();
        t = (GetListFloatKey(keys).ConvertAll(x => (int)x));
        return t;*/

        List<int> result = new List<int>();
        string s = GetKey(keys);
        if (s != null)
        {
            string[] items = s.Split(new char[] { ',' });
            int f;
            foreach (string item in items)
            {
                if (int.TryParse(item, out f))
                    result.Add(f);
            }
            return result;
        }
        else
        {
            return result;
        }
;

    }

    public void SetListIntKey(string key, List<int> Values)
    {

        StringBuilder sb = new StringBuilder();
        foreach (int value in Values)
        {
            sb.AppendFormat(",{0}", value);
        }
        if (Values.Count == 0)
        {
            SetKey(key, "");
        }
        else
        {
            SetKey(key, sb.ToString().Substring(1));
        }
    }
        /*---------------------------------
        *   P R I V A T E    M E T H O D S 
        * -------------------------------*/
    }

}

1 个答案:

答案 0 :(得分:1)

您所做的是将richtextbox中的“时间”设置为文本,而您没有更新ticksDisplayed变量:

richTextBox1.Text = optionsfile.GetKey("result");

时钟运行时,它将读取ticksDisplayed变量,它会加上或减去diff并显示结果。此时您的ticksDisplayed为零!然后,将小时跟踪栏更改为5,ticksDisplayed变为05:00:00(以小时为单位)。您还需要更新ticksDisplayed

richTextBox1.Text = optionsfile.GetKey("result");
//You need to update ticksDisplayed also!
TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
ticksDisplayed = ctimeSpan.Ticks;
....
....

如果您按下了start button,那本来可以正常工作(因为它设置了ticksDisplayed值),但是您可能没有设置正确的ticksDisplayed值就启动了计时器和时钟。

要将跟踪栏更改为跟随时间,只需在GetTimeString()中添加以下代码即可:

private string GetTimeString(TimeSpan elapsed)
{
    result = string.Empty;

    //calculate difference in ticks
    diff = elapsed.Ticks - previousTicks;

    if (radioButton1.Checked == true)
    { //counting up
        ticksDisplayed += diff;
    }
    else
    { //counting down
        ticksDisplayed -= diff;
    }

    if (ticksDisplayed < 0)
    {
        ticksDisplayed = 0;
    }

    //Make ticksDisplayed to regular time to display in richtextbox
    TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);

    //HERE
    if( trackBarHours.Value != ctimeSpan.Hours ){ trackBarHours.Value = ctimeSpan.Hours; }
    if( trackBarMinutes.Value != ctimeSpan.Minutes){ trackBarMinutes.Value = ctimeSpan.Minutes; }
    if( trackBarSeconds.Value != ctimeSpan.Seconds){ trackBarSeconds.Value = ctimeSpan.Seconds; }

    result = string.Format("{0:00}:{1:00}:{2:00}.{3:000}",
        ctimeSpan.Hours,
        ctimeSpan.Minutes,
        ctimeSpan.Seconds,
        ctimeSpan.Milliseconds);

    previousTicks = elapsed.Ticks;

    return result;
}