Question

I have a timer, how starts, when the text in a label appears and stop when you click on a button. Now i want to stop the reaktiontime and save it in a list, which i want to sort, so i can give out the fastest and lowest reaktiontime in a label. but in my code every time it shows 00:00:00 in the messagebox :(

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

}
Était-ce utile?

La solution

In a first run i tried to alter your code so that it should run. But i found so many (coding style) issues within there that i simply wrote a completely new example. It also has some minor issues (e.g. size of buttons; it is possible that a color button occurs twice). But it hopefully shows you how TimeSpan and all the other parts can work together.

The Form1.cs file:

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

The Form1.Designer.cs file:

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;


}

Autres conseils

I think your problem here is that the resolution of DateTime is less than the intervals that you are trying to measure.

Instead of using DateTime, try the following:

Create a private Stopwatch field called stopwatch.

Stopwatch stopwatch = new Stopwatch();

Then change your tick handler to:

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

However, I'm also not sure about your logic to do with when you restart the stopwatch. (Where I put stopwatch.Restart().) Do you really want to keep restarting the stopwatch at that point?

use:

ts = Time1.subtract(Time2);

How to calculate datetime diffrence:

How to calculate hours between 2 different dates in c#

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top