更新图片框
本文关键字:更新 | 更新日期: 2023-09-27 17:56:44
我希望我的图片框每 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;
}
不要在计时器事件中进入任何睡眠状态,除非在非常特殊的情况下,否则避免使用 DoEvents()。
Update()和 Refresh() 是无用的。
如果确实需要在计时器事件中显示对话框,请在对话框之前禁用计时器,然后在之后启用它。
如果需要 Invalidate,请将其放在 DrawString 之后。
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;
}