winforms 我如何保存和加载回来,并继续每次运行应用程序的时间跨度毫秒值?

n6lpvg4x  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(92)

问题是你不能给时间跨度指定只读的毫秒数。

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;
            diff = elapsed.Ticks - previousTicks;

            if (radioButton1.Checked == true)
            {
                ticksDisplayed += diff;
            }
            else
            {
                if (countingDown)
                {
                    ticksDisplayed += diff;
                }
                else
                {
                    ticksDisplayed -= diff;
                }
            }

            if (ticksDisplayed < 0)
            {
                ticksDisplayed = 0;

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

                timer1.Enabled = false;
            }

            ctimeSpan = new TimeSpan(ticksDisplayed);
            timeTarget(ctimeSpan);

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

在此处调用UpdateTime

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

保存时间跨度毫秒不是问题,问题是如何读回它,因为你不能赋值给ctimeSpan. Milliseconds。
我可以在更多的地方保存字符串。格式变量的结果,但有时如果我试图在form 1关闭事件中保存它,结果是空的。所以我更喜欢在特定情况下只保存和加载ctimeSpan.Milliseconds值。
使用form 1的完整代码和屏幕截图进行编辑。
现在我使用3个trackBar来保存和加载时间跨度小时,分钟,秒,但因为我不想添加另一个trackBar的毫秒,这是我想保存/加载的毫秒分开的原因。
在我的应用程序中,我使用了自己的OptionsFile类,但这并不重要,我想找到逻辑,以及如何保存/加载与我保存/加载小时、分钟、秒的方式分开的毫秒。

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;
        private bool runOnStart = false;
        private bool countingDown = false;
        private TimeSpan ctimeSpan;

        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");

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

            radioButton1.Checked = GetBool("radiobutton1");
            timeTargetchkbox.Checked = GetBool("timetargetcheckbox");

            timeTargetchkboxState();

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

            if (ticksDisplayed == 0)
                radioButton1.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;
            }

            runOnStart = GetBool("runonstart");
            if (runOnStart == true)
            {
                autoRunOnStart.Checked = true;
                StartOnRun();
            }
            else
            {
                autoRunOnStart.Checked = false;
            }
        }

        private void timeTargetchkboxState()
        {
            if (timeTargetchkbox.Checked == false)
            {
                dateTimePicker1.Enabled = false;
            }
            else
            {
                dateTimePicker1.Enabled = true;
            }
        }

        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;
            diff = elapsed.Ticks - previousTicks;

            if (radioButton1.Checked == true)
            {
                ticksDisplayed += diff;
            }
            else
            {
                if (countingDown)
                {
                    ticksDisplayed += diff;
                }
                else
                {
                    ticksDisplayed -= diff;
                }
            }

            if (ticksDisplayed < 0)
            {
                ticksDisplayed = 0;

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

                timer1.Enabled = false;
            }

            ctimeSpan = new TimeSpan(ticksDisplayed);
            timeTarget(ctimeSpan);

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

        private void timeTarget(TimeSpan ctimeSpan)
        {
            if (dateTimePicker1.Value.Hour == ctimeSpan.Hours
                && dateTimePicker1.Value.Minute == ctimeSpan.Minutes
                && dateTimePicker1.Value.Second == ctimeSpan.Seconds
                && timeTargetchkbox.Checked == true)
            {
                //ticksDisplayed = 0;
                if (btnPause.Text == "PAUSE")
                {
                    btnPause.Text = "CONTINUE";
                    watch.Stop();
                    timer1.Enabled = false;
                }
            }
            else
            {
                if (btnStart.Text == "STOP")
                {
                    btnPause.Text = "PAUSE";
                    watch.Start();
                    timer1.Enabled = true;
                }
            }
            timeTargetchkboxState();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

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

                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;
                btnReset.Enabled = false;
                trackBarHours.Value = 0;
                trackBarMinutes.Value = 0;
                trackBarSeconds.Value = 0;

                TimeSpan ctimeSpan = new TimeSpan(0, trackBarHours.Value, trackBarMinutes.Value, trackBarSeconds.Value, 0);
                diff = 0;
                previousTicks = 0;
                ticksDisplayed = ctimeSpan.Ticks;
                watch.Reset();
                timer1.Enabled = false;
                UpdateTime();
            }
        }

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

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

            if (radioButton2.Checked && ticksDisplayed == 0)
            {
                countingDown = true;
                radioButton2.Checked = false;
                radioButton1.Checked = true;
            }

            UpdateTime();
        }

        private void trackBarHours_Scroll(object sender, EventArgs e)
        {
            TimeSpan ctimeSpan = new TimeSpan(ticksDisplayed);
            TimeSpan htimeSpan = new TimeSpan(ctimeSpan.Days, trackBarHours.Value, ctimeSpan.Minutes, ctimeSpan.Seconds, ctimeSpan.Milliseconds);

            ticksDisplayed = htimeSpan.Ticks;

            TrackbarsScrollStates();

            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;

            TrackbarsScrollStates();

            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;

            TrackbarsScrollStates();

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

            UpdateTime();
        }

        private void TrackbarsScrollStates()
        {
            if (trackBarSeconds.Value == 0 && trackBarHours.Value == 0 && trackBarMinutes.Value == 0)
                btnReset.Enabled = false;
            if (trackBarSeconds.Value > 0 || trackBarHours.Value > 0 || trackBarMinutes.Value > 0)
                btnReset.Enabled = true;
        }

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

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            optionsfile.SetKey("trackbarhours", trackBarHours.Value.ToString());
            optionsfile.SetKey("trackbarminutes", trackBarMinutes.Value.ToString());
            optionsfile.SetKey("trackbarseconds", trackBarSeconds.Value.ToString());
        }

        private void btnPause_Click(object sender, EventArgs e)
        {
            Pause();
        }

        private void Pause()
        {
            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();
        }

        private void autoRunOnStart_CheckedChanged(object sender, EventArgs e)
        {
            if (autoRunOnStart.Checked)
            {
                runOnStart = true;
            }
            else
            {
                runOnStart = false;
            }

            optionsfile.SetKey("runonstart", runOnStart.ToString());
        }

        private void radioButton2_CheckedChanged(object sender, EventArgs e)
        {
            countingDown = false;
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            btnStart.Focus();
            timeTarget(ctimeSpan);
        }

        private void timeTargetchkbox_CheckedChanged(object sender, EventArgs e)
        {
            if (timeTargetchkbox.Checked == false)
            {
                dateTimePicker1.Enabled = false;
            }
            else
            {
                dateTimePicker1.Enabled = true;
            }
            optionsfile.SetKey("timetargetcheckbox", timeTargetchkbox.Checked.ToString());
        }

        private void StartOnRun()
        {
            watch.Reset();

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

        private bool GetBool(string keyname)
        {
            string radiobutton1 = optionsfile.GetKey(keyname);
            bool b = false;

            if (radiobutton1 != null)
            {
                bool.TryParse(radiobutton1.Trim(), out b);
            }

            return b;
        }
    }
}

以及显示应用程序的屏幕截图:

gzszwxb4

gzszwxb41#

我将尝试进行概括,因为这个问题没有显示出试图完成什么的明确意图,所以很难给予一个明确的答案。
有很多方法可以示例化新的TimeSpan,如下所述:https://learn.microsoft.com/en-us/dotnet/api/system.timespan?view=net-7.0#instantiating-a-timespan-value
如果我试图持久化并加载一个TimeSpan,那么我个人会考虑使用ticks值。

// Create a TimeSpan to test with.
var randomTimer = Stopwatch.StartNew();
Thread.Sleep((new Random()).Next(1000,5000)); // Wait 1 to 5 second to get a meaningful value in the example TimeSpan.
var myTimeSpanToSave = randomTimer.Elapsed;

// Save the total ticks here.
var totalEllapsedTicks = myTimeSpanToSave.Ticks;

// Load total ticks and instantiate a new TimeSpan
var newTimeSpanFromTicks = new TimeSpan(totalEllapsedTicks);

我不知道你为什么要修改TimeSpan的毫秒部分,但是假设有一个合理的理由,那么这里有几个想法。
想法1 -使用原始对象中的值创建一个新的TimeSpan,并仅替换Millisecond属性。

var customMilliseconds = 123;
var newTimeSpanWithCustomMilliseconds = new TimeSpan(myOriginalTimeSpan.Days, myOriginalTimeSpan.Hours, myOriginalTimeSpan.Minutes, myOriginalTimeSpan.Seconds, customMilliseconds);

想法2 -使用“添加”清除当前毫秒值并插入加载的值。

var customMilliseconds = new TimeSpan(0, 0, 0, 0, 123);
var oldMillisecondValueToRemove = new TimeSpan(0, 0, 0, 0, myOriginalTimeSpan.Milliseconds);
myOriginalTimeSpan.Add(-oldMillisecondValueToRemove);
myOriginalTimeSpan.Add(customMilliseconds);

相关问题