我希望我的图片框每2秒更新一次字符串/文本(并删除旧文本)。我在这里制作了一些代码,但它没有显示任何内容:
namespace WindowsFormsApplication2
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void Form2_Load(object sender, EventArgs e)
{
}
static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
static bool exitFlag = false;
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
var image = new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height);
var font = new Font("TimesNewRoman", 30, FontStyle.Bold, GraphicsUnit.Pixel);
var graphics = Graphics.FromImage(image);
graphics.DrawString("Hi", font, Brushes.White, new Point(350, 0));
this.pictureBox1.Image = image;
System.Threading.Thread.Sleep(1000);
pictureBox1.Invalidate();
graphics.DrawString("Tell me your name...", font, Brushes.White, new Point(100, 0));
this.pictureBox1.Image = image;
this.pictureBox1.Update();
this.pictureBox1.Refresh();
//dialog box in here
}
public int ActivateTimer()
{
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Interval = 1000;
myTimer.Start();
while (exitFlag == false)
{
Application.DoEvents();
}
return 0;
}
答案 0 :(得分:0)
除非在非常特殊的情况下,否则不要在计时器事件中进行任何睡眠并避免使用DoEvents()。
Update()和Refresh()没用。
如果您确实需要在计时器事件中显示一个对话框,请在对话前禁用计时器并在之后启用它。
如果您需要Invalidate,请将其放在DrawString之后。
答案 1 :(得分:0)
private void ActivateTimer ( )
{
myTimer.Interval = 1000;
myTimer.Enabled = true;
myTimer.Tick += new EventHandler(TimerEventProcessor);
myTimer.Start();
}
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
var image = new Bitmap(this.pictureBox1.Width, this.pictureBox1.Height);
var font = new Font("TimesNewRoman", 30, FontStyle.Bold, GraphicsUnit.Pixel);
var graphics = Graphics.FromImage(image);
graphics.DrawString("Hi", font, Brushes.White, new Point(350, 0));
this.pictureBox1.Image = image;
graphics.DrawString("Tell me your name...", font, Brushes.White, new Point(100, 0));
this.pictureBox1.Image = image;
}