繁体   English   中英

如何在不使用计时器的情况下以Windows形式显示秒表

[英]how to show stopwatch in windows form without using timers

我是这个领域的新蜜蜂。 我在Windows窗体中使用计时器,该计时器以固定的时间间隔从数据库中获取数据。 现在我希望我的计时器重新发送邮件,但是我需要在屏幕上显示秒表。 有什么办法吗? 代码在这里.....

public partial class Form2 : Form
{
    private Timer _timer;
    int count = 0;
    // The last time the timer was started
    private DateTime _startTime = DateTime.MinValue;

    // Time between now and when the timer was started last
    private TimeSpan _currentElapsedTime = TimeSpan.Zero;

    // Time between now and the first time timer was started after a reset
    private TimeSpan _totalElapsedTime = TimeSpan.Zero;

    // Whether or not the timer is currently running
    private bool _timerRunning = false;
    public Form2(String UserName)
    {
        InitializeComponent();
        _timer = new Timer();
        _timer.Interval = 1000;
        _timer.Tick += new EventHandler(timer_Tick);
        label4.Text = UserName; 

    }


    private void richTextBox2_TextChanged(object sender, EventArgs e)
    {

    }


    private void timer_Tick(object sender, EventArgs e)
    {

        count = count + 1;
        var timeSinceStartTime = DateTime.Now - _startTime;
        timeSinceStartTime = new TimeSpan(timeSinceStartTime.Hours,
                                          timeSinceStartTime.Minutes,
                                          timeSinceStartTime.Seconds);

        // The current elapsed time is the time since the start button was
        // clicked, plus the total time elapsed since the last reset
        _currentElapsedTime = timeSinceStartTime + _totalElapsedTime;

        // These are just two Label controls which display the current 
        // elapsed time and total elapsed time

        label3.Text = timeSinceStartTime.ToString();
        String str1, str2;
        SqlDataReader rd1, rd2;
        SqlConnection Con = new SqlConnection("Data Source=216.218.224.238;Database=chatapp;Uid=chatappuser;pwd=1234@ChatAppUser;MultipleActiveResultSets=true;");
        // SqlConnection Con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Test;User ID=;Password=;Connection Timeout=600");
        Con.Open();

        rd1 = new SqlCommand("select top 1 Chat from chat where  where email ='" + label4.Text + "'order by id Desc", Con).ExecuteReader();
        rd1.Read();
        str1 = rd1["Chat"].ToString();
        rd1.Close();
        rd2 = new SqlCommand("select top 1 UserInitial from chat where email ='" + label4.Text + "' order by id Desc", Con).ExecuteReader();
        rd2.Read();
        str2 = rd2["UserInitial"].ToString();
        rd2.Close();
        if (str1 != str2)
        {
            SqlDataReader rd3, rd4;
            rd3 = new SqlCommand("select top 1 UserInitial from chat  where email ='" + label4.Text + "'order by id desc", Con).ExecuteReader();

            richTextBox1.Text = richTextBox1.Text + " <br /> " + rd3.Read();
            rd3.Close();
            rd4 = new SqlCommand("Update top 1 chat set Chat = UserInitial  where email ='" + label4.Text + "'order by id desc", Con).ExecuteReader();
            rd4.Read();
            rd4.Close();
            Con.Close();
        }

    }

    private void button1_Click(object sender, EventArgs e)
    {

        if (!_timerRunning)
        {
            // Set the start time to Now
            _startTime = DateTime.Now;

            // Store the total elapsed time so far
            _totalElapsedTime = _currentElapsedTime;

            _timer.Start();
            _timerRunning = true;
        }
        else // If the timer is already running
        {
            _timer.Stop();
            _timerRunning = false;
        }
        SqlDataReader rd5;
        SqlConnection Con = new SqlConnection("Data Source=216.218.224.238;Database=chatapp;Uid=chatappuser;pwd=1234@ChatAppUser;MultipleActiveResultSets=true;");
        // SqlConnection Con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Test;User ID=;Password=;Connection Timeout=600");
        Con.Open();
        richTextBox1.Text = richTextBox1.Text + "<br />Me:" + richTextBox2.Text;
        rd5 = new SqlCommand("Update chat set UserInitial ='" + richTextBox2.Text + "' order by id Desc where email ='" + label4.Text + "'", Con).ExecuteReader();
        rd5.Read();
        rd5.Close();
        Con.Close();
    }


    private void button3_Click(object sender, EventArgs e)
    {
        _timer.Stop();
        _timerRunning = false;

        // Reset the elapsed time TimeSpan objects
        _totalElapsedTime = TimeSpan.Zero;
        _currentElapsedTime = TimeSpan.Zero;
        label3.Text = _totalElapsedTime.ToString();  
        MessageBox.Show(count.ToString());
        count = 0;
    }

提前致谢.....

您可以使用StopWatch类获取Elapsed的时间

从MSDN:

提供一组方法和属性,可用于准确测量经过的时间。

步骤1:StopWatch变量创建为类级别变量。

步骤2:每当您要开始计数时,调用Start()方法。

第3步:timer_tick事件时,可以采取由USIG经过的Totalseconds stopwatch.Elapsed.Seconds

尝试这个:

Stopwatch watch = new Stopwatch();
watch.Start();
private void timer_Tick(object sender, EventArgs e)
{
  label1.Text = watch.Elapsed.Seconds.ToString();
}

您可以使用BackgroundWorker

在事件OnDoWork内,您可以添加逻辑以从数据库中获取数据并每隔固定的间隔更新接口。 您可以启动和停止,请单击链接获取有关如何使用它的更多详细信息。

编辑

我做了一个小演示,以演示后台工作者的用法。 无论如何,您应该改善从数据库检索数据的逻辑。 注意:根据查询运行的速度,如果查询运行缓慢,则应在不同线程上执行此操作,检索数据并显示秒表,否则秒表值将是错误的。

private bool _running;
private BackgroundWorker _bw;
private Stopwatch _watch;
private System.Timers.Timer _timer;
    public Form1()
    {
        InitializeComponent();
    }

    private void BwOnProgressChanged(object sender, ProgressChangedEventArgs e)
    {

    }

    private void BwOnDoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;

        while (_running)
        {
            if ((worker.CancellationPending == true))
            {
                e.Cancel = true;
                return;
            }
            else
            {                    
                // Perform a time consuming operation and report progress.
                String str1, str2;
                SqlDataReader rd1, rd2;
                SqlConnection Con =
                    new SqlConnection(
                        "Data Source=216.218.224.238;Database=chatapp;Uid=chatappuser;pwd=1234@ChatAppUser;MultipleActiveResultSets=true;");
                // SqlConnection Con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Test;User ID=;Password=;Connection Timeout=600");
                Con.Open();

                rd1 =
                    new SqlCommand(
                        "select top 1 Chat from chat where  where email ='" + label4.Text + "'order by id Desc", Con)
                        .ExecuteReader();
                rd1.Read();
                str1 = rd1["Chat"].ToString();
                rd1.Close();
                rd2 =
                    new SqlCommand(
                        "select top 1 UserInitial from chat where email ='" + label4.Text + "' order by id Desc",
                        Con)
                        .ExecuteReader();
                rd2.Read();
                str2 = rd2["UserInitial"].ToString();
                rd2.Close();
                if (str1 != str2)
                {
                    SqlDataReader rd3, rd4;
                    rd3 =
                        new SqlCommand(
                            "select top 1 UserInitial from chat  where email ='" + label4.Text + "'order by id desc",
                            Con).ExecuteReader();


                    var value = rd3.Read();
                    rd3.Close();

                    if (richTextBox1.InvokeRequired)
                    {
                        richTextBox1.BeginInvoke(
                            new MethodInvoker(() => richTextBox1.Text += richTextBox1.Text + " <br /> " + value));
                    }
                    else
                    {
                        richTextBox1.Text = richTextBox1.Text + " <br /> " + value;
                    }
                    rd4 =
                        new SqlCommand(
                            "Update top 1 chat set Chat = UserInitial  where email ='" + label4.Text +
                            "'order by id desc", Con).ExecuteReader();
                    rd4.Read();
                    rd4.Close();
                    Con.Close();
                }

                Thread.Sleep(1000); //sleep 1 second

            }
            //System.Threading.Thread.Sleep(500);
        }
    }
void _timer_Elapsed(object sender, ElapsedEventArgs e)
 {
        if (label3.InvokeRequired)
        {
            label3.BeginInvoke(new MethodInvoker(() => label3.Text = _watch.Elapsed.Seconds.ToString()));
        }
        else
        {
            label3.Text = _watch.Elapsed.Seconds.ToString();
        }
    }


    private void button1_Click(object sender, EventArgs e)
    {
        _running = true;
        _watch = new Stopwatch();
        _watch.Start();
        _bw.RunWorkerAsync();
        //start the timer
        _timer.Start();

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        _bw = new BackgroundWorker();
        _bw.WorkerReportsProgress = true;
        _bw.DoWork += BwOnDoWork;
        _bw.ProgressChanged += BwOnProgressChanged;

        // instantiate the timer
        _timer = new System.Timers.Timer();
        _timer.Interval = 1000;
        _timer.Elapsed += _timer_Elapsed;

    }


    private void button2_Click(object sender, EventArgs e)
    {
        _running = false;
        _bw.CancelAsync();
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
       //dispose resources
         _bw.CancelAsync();
        _bw.Dispose();
        _watch.Stop();           
        _timer.Dispose();
    }

要删除Thread.Sleep(1000)您可以将计时器仅用于表单线程上的秒表,并将更新的聊天工作分配给后台工作人员。 这样,经过的时间将更加准确。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM