使用计时器更新Windows窗体上的标签 [英] Update label on windows form using Timer

查看:161
本文介绍了使用计时器更新Windows窗体上的标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Windows窗体的Label控件上显示经过的时间.为此,我正在使用System.Timers.timer,但无法通过按钮单击事件的经过时间来更新Label.
尝试过Timer的Timer tick事件,但是没有运气,我想在用户单击处理"按钮后立即更新标签控件的经过时间,直到所有功能在单击按钮时都执行.
请帮忙.

参考代码:

I want to display time elapsed on Label control on windows form. for that i am using System.Timers.timer but unable to update Label with the elapsed time on button click event.
tried Timer tick event of Timer but no luck, i want to update elapsed time on label control as soon as user click Process button till all the functions get executed on button click.
Please help.

code for reference :

dim mdate as date
private sub btnprocess_click()
mdate=date.now

timer.enabled=true
timer.start()
timer.interval=100

'below functions take much time in processing
'Approx 20 to 30 minutes to complete all functionalities.

function1
function2
function3

timer.enabled=false

end sub

private sub timer_tick()
Dim ts As TimeSpan = DateTime.Now.Subtract(mDate)
lblelapsed.Text = ts.Hours  & ":" & ts.Minutes  & ":" & ts.Seconds 
Update()
end sub

推荐答案

我的背景是C#,您需要将代码转换为VB.Net,
像这样尝试:
my background is C# you need to convert the code to VB.Net,
Try like this:
DateTime mdate;
System.Timers.Timer tim;
bool isProcessing = true;

private void button1_Click(object sender, EventArgs e)
{
    mdate = DateTime.Now;
    tim = new System.Timers.Timer(1000);
    tim.Elapsed += new System.Timers.ElapsedEventHandler(tim_Elapsed);
    tim.Start();

    new Thread(new ThreadStart(doTheJob)).Start();

    while (isProcessing)
    {
        Thread.Sleep(100);
        Application.DoEvents();
    }
    tim.Stop();
}

private void doTheJob()
{
    //all your code like
    //function1
    //function2
    //function3
    isProcessing = false;
}

void tim_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
    TimeSpan ts = DateTime.Now.Subtract(mdate);

    label1.Text = ts.Hours + ":" + ts.Minutes + ":" + ts.Seconds + ":" + ts.Milliseconds;

    Application.DoEvents();
}

现在我们使用的是System.Timers.Timer而不是System.Forms.Timer.

now we are using System.Timers.Timer instead of System.Forms.Timer.


使用此
字符串str1 = System.DateTime.Now.ToString("hh-mm-ss");

您可以获取系统时间...每当用户单击按钮将该值存储为开始时间时,在再次停止该过程时,请使用该System.DateTime.Now();现在您可以获取停止时间..计算差值可以得到经过的时间. .我希望这可能对您有帮助....
use this
string str1=System.DateTime.Now.ToString("hh-mm-ss");

you can get system time...whenever user clicking button store that value as start time.while stop the process again use that System.DateTime.Now();now u can get stopped time..calculate difference you can get elapsed time..i hope this may helpful for you....


这篇关于使用计时器更新Windows窗体上的标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆