Why when changing one of the trackBars values it's reseting the other values of the watch to 0?

The code:

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();
        }
    }
}

Now for example when running the application and it's loading the values from a saved text file the values of the trackBars fro example: Hours = 1 Minutes = 10 Seconds = 50

If now I will change one of the trackBars values the other values in the richTextBox will change to 00 the other two trackBars will keep in the same values but the values in the riachTextBox will be change to 00 for both trackBars.

For example I'm running the application first time in the richTextBox the time is: 01:10:50.000 the trackBars values are the same 1 10 50 now I'm changing the value of 01 the hours trackBar to 05 the other two trackBars will stay on values 10 and 50 but in the richTextBox the 10 and 50 will be reset to 00:00.

Can't figure out why.

This is the class t=for saving/loading the settings:

/*----------------------------------------------------------------
 * 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 answer

  • answered 2018-10-09 17:45 γηράσκω δ' αεί πολλά διδασκόμε

    What you did is set the "time" in richtextbox as text while you didn't update the ticksDisplayed variable:

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

    When the clock runs it reads the ticksDisplayed variable it adds or subtracts the diff and presents the result. Your ticksDisplayed is zero at this point! Then you change the hour trackbar to 5 and the ticksDisplayed becomes 05:00:00, in ticks of cource. You need to update ticksDisplayed also:

    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;
    ....
    ....
    

    If you had pressed the start button it whould have worked fine(cause it sets the ticksDisplayed value) but you probably started the timer and the clock without setting the correct ticksDisplayed value.

    To change the trackbars to follow the time just add this code in 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;
    }