c#timeSpan如何工作?

时间:2013-10-30 10:29:05

标签: c# list sorting timespan

我有一个计时器,当标签中的文字出现时,如何启动,当您点击按钮时停止。现在我想停止reaktiontime并将其保存在列表中,我想对其进行排序,这样我就可以在标签中给出最快和最低的reaktiontime。但在我的代码中,每次它在消息框中显示00:00:00 :(

public partial class Form1 : Form
{
    Random r = new Random();
    Random Farbe = new Random();
    bool Start_MouseClick;
    IList<string> Reaktionszeitliste = new List<string>() {};
    IList<Color> myColors = new[] { Color.Red, Color.Blue, Color.Green, Color.White, Color.Yellow };
    string[] colors = { "Rot", "Blau", "Grün", "Gelb", "Weiß" };
    int Timeleft = 5;
    int summe = 0, z;
    string Reaktionszeit;
    int Zeit;
    int Spielzuege = 0;
    DateTime Time1;
    DateTime Time2;
    TimeSpan ts;

    private void btnRot_Click(object sender, EventArgs e)
    {
        Spielzuege = Spielzuege + 1;

        timMessung.Stop(); 

        if (Start_MouseClick == true)
     {
        int summe = 0, z;

        lblAnzeige.Text = " ";

        while (summe <= 0)
        {
            z = r.Next(1, 6);
            summe = summe + z;    
        }

        lblAnzeige.Text += colors[summe - 1] + "\n";
        Zeit = 0;
        timMessung.Enabled = true;

            if (ckbExtrem.Checked == false)
            {
                lblAnzeige.ForeColor = myColors[Farbe.Next(myColors.Count)];
            }
            else
            {
                lblAnzeige.ForeColor = Color.FromArgb(Farbe.Next(256), Farbe.Next(256), Farbe.Next(256));
            }
            if (Spielzuege == 15)
            {
                if (txbPlayer2.Text != "")
                {
                    MessageBox.Show("Spieler 2: Machen Sie sich bereit!");
                }
                else
                {
                    MessageBox.Show(Convert.ToString(ts));                       
            }
            }
        }
    }

private void txbStart_MouseClick(object sender, MouseEventArgs e)
{

    if (txbPlayer1.Text == "" && txbPlayer2.Text == "")
    {
        MessageBox.Show("Bitte geben Sie Spielername(n) ein!");
    }
    else
    {
        timVerzögerung.Enabled = true;
        panel1.Visible = false;


        lblAnzeige.Text = " ";
        txbStart.Visible = false;
        textBox1.Visible = false;
        Start_MouseClick = true;

        while (summe <= 0)
        {
            z = r.Next(1, 6);
            summe = summe + z;
        }
    }               
}

private void timMessung_Tick(object sender, EventArgs e)
{
    if (timMessung.Enabled == true)
    {
        Time1 = DateTime.Now;
    }
    else
    {
        Time2 = DateTime.Now;
        ts = Time1 - Time2;
        int differenceInMilli = ts.Milliseconds;
    }

}

3 个答案:

答案 0 :(得分:0)

我认为您的问题是DateTime的分辨率小于您尝试测量的间隔。

请尝试以下方法,而不是使用DateTime

创建一个名为Stopwatch的私人stopwatch字段。

Stopwatch stopwatch = new Stopwatch();

然后将您的tick处理程序更改为:

private void timMessung_Tick(object sender, EventArgs e)
{
    if (timMessung.Enabled == true)
    {
        stopwatch.Restart();
    }
    else
    {
        ts.stopwatch.Elapsed();
    }
}

但是,当你重新启动秒表时,我也不确定你的逻辑。 (我把stopwatch.Restart()放在哪里。)你真的想继续重新启动秒表吗?

答案 1 :(得分:0)

使用:

ts = Time1.subtract(Time2);

如何计算日期时间差异:

How to calculate hours between 2 different dates in c#

答案 2 :(得分:0)

在第一次运行中,我试图改变你的代码,以便它运行。但我在那里发现了很多(编码风格)问题,我只是写了一个全新的例子。它也有一些小问题(例如按钮的大小;颜色按钮可能出现两次)。但它希望向您展示TimeSpan以及所有其他部分如何协同工作。

Form1.cs文件:

public partial class Form1 : Form
{
    private Random _Random;
    private List<TimeSpan> _ReactionTimes;
    private Stopwatch _Stopwatch;

    public Form1()
    {
        InitializeComponent();
        _Stopwatch = new Stopwatch();
        _Random = new Random(42);
        _ReactionTimes = new List<TimeSpan>();
    }

    private Button CreateButton(Color color)
    {
        var button = new Button();
        button.Click += OnColorButtonClick;
        button.BackColor = color;
        button.Text = color.Name;

        return button;
    }

    private Button GetRandomButton()
    {
        var randomIndex = _Random.Next(0, flowLayoutPanel.Controls.Count);
        return (Button)flowLayoutPanel.Controls[randomIndex];
    }

    private Color GetRandomColor()
    {
        var randomKnownColor = (KnownColor)_Random.Next((int)KnownColor.AliceBlue, (int)KnownColor.ButtonFace);
        return Color.FromKnownColor(randomKnownColor);
    }

    private void InitializeColorButtons(int numberOfColors)
    {
        var buttons = Enumerable.Range(1, numberOfColors)
                                .Select(index => GetRandomColor())
                                .Select(color => CreateButton(color));

        foreach (var button in buttons)
        {
            flowLayoutPanel.Controls.Add(button);
        }
    }

    private void OnButtonStartClick(object sender, EventArgs e)
    {
        InitializeColorButtons((int)numericUpDownColors.Value);
        StartMeasurement();
    }

    private void OnColorButtonClick(object sender, EventArgs e)
    {
        var button = (Button)sender;

        if (button.Text != labelColorToClick.Text)
        {
            errorProviderWrongButton.SetIconPadding(button, -20);
            errorProviderWrongButton.SetError(button, "Sorry, wrong button.");
            return;
        }

        StopMeasurement();
        _ReactionTimes.Add(_Stopwatch.Elapsed);
        UpdateSummary();
    }

    private void StartMeasurement()
    {
        buttonStart.Enabled = false;
        numericUpDownColors.Enabled = false;
        labelColorToClick.Text = GetRandomButton().Text;

        _Stopwatch.Reset();
        _Stopwatch.Start();
    }

    private void StopMeasurement()
    {
        _Stopwatch.Stop();
        errorProviderWrongButton.Clear();
        flowLayoutPanel.Controls.Clear();

        numericUpDownColors.Enabled = true;
        buttonStart.Enabled = true;
        labelColorToClick.Text = String.Empty;
    }

    private void UpdateSummary()
    {
        labelSummary.Text = String.Format("Current: {0:0.000}    Minimum: {1:0.000}    Maximum: {2:0.000}", _ReactionTimes.Last().TotalSeconds, _ReactionTimes.Min().TotalSeconds, _ReactionTimes.Max().TotalSeconds);
    }
}

Form1.Designer.cs文件:

partial class Form1
{
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;

    /// <summary>
    /// Clean up any resources being used.
    /// </summary>
    /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            components.Dispose();
        }
        base.Dispose(disposing);
    }

    #region Windows Form Designer generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.flowLayoutPanel = new System.Windows.Forms.FlowLayoutPanel();
        this.labelColorToClick = new System.Windows.Forms.Label();
        this.buttonStart = new System.Windows.Forms.Button();
        this.labelSummaryHeader = new System.Windows.Forms.Label();
        this.labelSummary = new System.Windows.Forms.Label();
        this.errorProviderWrongButton = new System.Windows.Forms.ErrorProvider(this.components);
        this.numericUpDownColors = new System.Windows.Forms.NumericUpDown();
        ((System.ComponentModel.ISupportInitialize)(this.errorProviderWrongButton)).BeginInit();
        ((System.ComponentModel.ISupportInitialize)(this.numericUpDownColors)).BeginInit();
        this.SuspendLayout();
        // 
        // flowLayoutPanel
        // 
        this.flowLayoutPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
        | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.flowLayoutPanel.Location = new System.Drawing.Point(12, 41);
        this.flowLayoutPanel.Name = "flowLayoutPanel";
        this.flowLayoutPanel.Size = new System.Drawing.Size(560, 386);
        this.flowLayoutPanel.TabIndex = 0;
        // 
        // labelColorToClick
        // 
        this.labelColorToClick.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
        | System.Windows.Forms.AnchorStyles.Right)));
        this.labelColorToClick.Location = new System.Drawing.Point(174, 12);
        this.labelColorToClick.Name = "labelColorToClick";
        this.labelColorToClick.Size = new System.Drawing.Size(398, 23);
        this.labelColorToClick.TabIndex = 1;
        this.labelColorToClick.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
        // 
        // buttonStart
        // 
        this.buttonStart.Location = new System.Drawing.Point(93, 12);
        this.buttonStart.Name = "buttonStart";
        this.buttonStart.Size = new System.Drawing.Size(75, 23);
        this.buttonStart.TabIndex = 2;
        this.buttonStart.Text = "Start";
        this.buttonStart.UseVisualStyleBackColor = true;
        this.buttonStart.Click += new System.EventHandler(this.OnButtonStartClick);
        // 
        // labelSummaryHeader
        // 
        this.labelSummaryHeader.Location = new System.Drawing.Point(12, 430);
        this.labelSummaryHeader.Name = "labelSummaryHeader";
        this.labelSummaryHeader.Size = new System.Drawing.Size(75, 23);
        this.labelSummaryHeader.TabIndex = 3;
        this.labelSummaryHeader.Text = "Summary:";
        this.labelSummaryHeader.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
        // 
        // labelSummary
        // 
        this.labelSummary.Location = new System.Drawing.Point(93, 430);
        this.labelSummary.Name = "labelSummary";
        this.labelSummary.Size = new System.Drawing.Size(479, 23);
        this.labelSummary.TabIndex = 4;
        this.labelSummary.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
        // 
        // errorProviderWrongButton
        // 
        this.errorProviderWrongButton.BlinkStyle = System.Windows.Forms.ErrorBlinkStyle.NeverBlink;
        this.errorProviderWrongButton.ContainerControl = this;
        // 
        // numericUpDownColors
        // 
        this.numericUpDownColors.Location = new System.Drawing.Point(12, 14);
        this.numericUpDownColors.Minimum = new decimal(new int[] {
        2,
        0,
        0,
        0});
        this.numericUpDownColors.Name = "numericUpDownColors";
        this.numericUpDownColors.Size = new System.Drawing.Size(75, 20);
        this.numericUpDownColors.TabIndex = 5;
        this.numericUpDownColors.Value = new decimal(new int[] {
        10,
        0,
        0,
        0});
        // 
        // Form1
        // 
        this.ClientSize = new System.Drawing.Size(584, 462);
        this.Controls.Add(this.numericUpDownColors);
        this.Controls.Add(this.labelSummary);
        this.Controls.Add(this.labelSummaryHeader);
        this.Controls.Add(this.buttonStart);
        this.Controls.Add(this.labelColorToClick);
        this.Controls.Add(this.flowLayoutPanel);
        this.Name = "Form1";
        ((System.ComponentModel.ISupportInitialize)(this.errorProviderWrongButton)).EndInit();
        ((System.ComponentModel.ISupportInitialize)(this.numericUpDownColors)).EndInit();
        this.ResumeLayout(false);

    }

    #endregion

    private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel;
    private System.Windows.Forms.Label labelColorToClick;
    private System.Windows.Forms.Button buttonStart;
    private System.Windows.Forms.Label labelSummaryHeader;
    private System.Windows.Forms.Label labelSummary;
    private System.Windows.Forms.ErrorProvider errorProviderWrongButton;
    private System.Windows.Forms.NumericUpDown numericUpDownColors;


}
相关问题