Update picturebox

392 views Asked by At

I want my picture box to update its string/text (and delete the old text) every 2 seconds. I made some code in here, but it doesn't show anything:

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;

 }
2

There are 2 answers

0
Graffito On

Don't make any sleep in a timer event and avoid DoEvents() except in very special cases.

Update() and Refresh() are useless.

If you really need to show a dialog box in the timer event, disable the timer before dialog and enable it after.

If you need Invalidate, put it after the DrawString.

0
Bogdan Mocanu On
 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;



    }