我有一個簡單的C#程序(在MS中的Visual Studio 2010進行)。 它是一個帶有單個按鈕的窗體。正如你可以看到它只是一個簡單的程序,但我堅持它。 我想了解C#中的C#定時器和全局變量。計時器爲什麼不啓動?
我希望它按下按鈕時執行以下操作 出現一個消息框(每秒)顯示自按鈕被按下以來秒數 。 它應該通過設置變量starttimer
爲真(在一個功能)工作,而在另一個函數時starttimer
等於true檢測它示出了在消息框中秒的時間。
然而,這似乎並沒有檢測starttimer
中其他功能等於true。所述startTimer所變量的目的是檢測按鈕按壓用於使用開始顯示該消息框每一秒。
那麼什麼來解決這個程序最簡單的方法?
PS當程序運行時沒有代碼starttimer
它每秒都會顯示消息框(當程序啓動時)。
程序窗口形式的圖片顯示-as你可以看到它很簡單,只有一個按鈕。
namespace timerprogram
{
public partial class doeverysecond : Form
{
int thetimeinsecs = 0;
bool starttimer = false;
private void Form1_Load(object sender, EventArgs e)
{
}
private void customfn(object source, ElapsedEventArgs e)
{
if (starttimer == true)
{
thetimeinsecs = thetimeinsecs + 1;
MessageBox.Show(thetimeinsecs.ToString());
}
}
public doeverysecond()
{
{
{
System.Timers.Timer mytimer = new System.Timers.Timer();
mytimer.Elapsed += new ElapsedEventHandler(customfn);
mytimer.Interval = 1000;
mytimer.Start();
}
}
}
private void button1_Click(object sender, EventArgs e)
{
starttimer = true;
}
}
}
你永遠不會調用doeverysecond – Derek
這是C#,而不是「C Sharp」 – Amy
而且你不想每次都創建一個新的計時器,那麼「mytimer」應該移出課程。 – Derek