私は C# が初めてで、時間文字列 (time と time0/time1) を表示する 2 つのラベル (label1 と label2) とテキストを変更する 1 つのボタン (一時停止/再生) で構成されるカスタム クロノメーターを作成しようとしています。クリックごとに一時停止から再生、またはその逆。label1 は datetime.now (hhmmss) によって作成された文字列変数である時間を示し、label2 は time0 を示し、「一時停止」ボタンをクリックしてもう一度「再生」すると time1 が表示されます (時間 1 は以下の式で計算されます)。
次のことを行います。
- システムの datetime.now (hhmmss) を取得し、時刻文字列に保存して、label1 に表示します
- 一時停止ボタンを押すと、timeの値が別の文字列time0に保存され、label2 で停止したことが示されます
- 再生ボタンを押すと、label1 の時刻と同期していないlabel2 の時刻 ( time1 ) が開始されます。
time1を計算するには、次の式を使用します。
time1 = DateTime.Now - ((DateTime.Now とtime0の差) - 1 秒)
2 つの文字列間の時間差を処理し、新しい時間time1を label2 と次のクリックのテキストとして使用する方法がわからないため、3 番目のポイントで立ち往生しています。
これは私の実際のコードです。それを完了するための助けをいただければ幸いです。ありがとうございます。
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
//time0
public int hh = 0;
public int mm = 0;
public int ss = 0;
//time
public string time = "";
public string time0 = "";
public bool IsPause = true;
public Timer t = new Timer();
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
//timer interval
t.Interval = 1000; //in millisecondi
t.Tick += new EventHandler(this.t_Tick);
//start timer form loads
t.Start(); //questo userà il metodo t_Tick()
}
//timer eventhandler
private void t_Tick(object sender, EventArgs e)
{
//get current time
hh = DateTime.Now.Hour;
mm = DateTime.Now.Minute;
ss = DateTime.Now.Second;
//padding leading zero
if(hh < 10)
{
time += "0" + hh;
}
else
{
time += hh;
}
time += ":";
if(mm < 10)
{
time += "0" + mm;
}
else
{
time += mm;
}
time += ":";
if (ss < 10)
{
time += "0" + ss;
}
else
{
time += ss;
}
//update labels
label1.Text = time;
if (IsPause == false) label2.Text = time0;
else label2.Text = time;
}
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "pause")
{
IsPause = false;
button1.Text = "play";
time0 = label1.Text;
}
else
{
IsPause = true;
button1.Text = "pause";
}
}
}
}