我在表单上有一个带有Label1的简单表单。我想要一个计时器,每10秒更新一次标签,并将值改为1,或者改为我想放在文本框中的文字。
这是我正在使用的代码。我已经能够让它闪烁一个消息框,然后更新消息框文本中的值,但除非我结束计时器,否则表单不会出现。我希望表单在调用计时器时显示和更新label1.Text字段值。
忽略代码的图形部分。
计划代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace DDHBindingExcelSheet
{
public partial class Form4 : Form
{
static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
static int alarmCounter = 1;
static bool exitFlag = false;
public Form4()
{
InitializeComponent();
}
private void Form4_Load(object sender, EventArgs e)
{
time();
}
private void TimerEventProcessor(Object myObject,
EventArgs myEventArgs)
{
myTimer.Stop();
// Displays a message box asking whether to continue running the timer.
// if (MessageBox.Show("Continue running?", "Count is: " + alarmCounter,
// MessageBoxButtons.YesNo) == DialogResult.Yes)
// {
// Restarts the timer and increments the counter.
alarmCounter += 1;
l.Text = alarmCounter.ToString(); ;
myTimer.Enabled = true;
// }
// else
// {
// Stops the timer.
// exitFlag = true;
// }
}
private void time()
{
/*Adds the event and the event handler for the method that will
process the timer event to the timer.*/
myTimer.Tick += new EventHandler(TimerEventProcessor);
// Sets the timer interval to 5 seconds.
myTimer.Interval = 5000;
myTimer.Start();
// Runs the timer, and raises the event.
while (exitFlag == false)
{
// Processes all the events in the queue.
Application.DoEvents();
}
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g;
Pen myPen = new Pen(Color.Black, 2);
Point sp = new Point(73, 73);//starting point sp
Point ep = new Point(250, 240);//ending point ep
g = this.CreateGraphics();//tells compiler that we are going to draw on this very form
g.DrawLine(myPen, sp, ep);
myPen.Width = 1;
myPen.Color = Color.Red;
g.DrawRectangle(myPen, 240, 230, 25, 25);
myPen.Width = 1;
myPen.Color = Color.Black;
g.DrawLine(myPen, sp, ep);
g.DrawEllipse(myPen, 0, 0, 500, 500);//you can see here we use 30,30 same width and height to draw a circle if they were different an ellipse would be drawn where as x and y are the upper right coordinates of a rectangle bounding this circle.
g.DrawEllipse(myPen, 250, 240, 5, 5);
}
}
}
答案 0 :(得分:2)
根本不要 EVER 致电Application.DoEvents()
如果您删除以下程序将按预期工作:
// Runs the timer, and raises the event.
while (exitFlag == false)
{
// Processes all the events in the queue.
Application.DoEvents();
}