michaelekins
michaelekins

Reputation: 579

PictureBox image not displayed by Form.Shown call

I have a form containing a TableLayoutPanel which has 1 row and 2 columns.

Column 1 contains a panel which contains a picture box. Column 2 is a text box.

I would like to display the form and then add text to the textbox one character at a time. Everything works perfectly except the picturebox image isn't displayed until the textbox has finished populating.

class Program
{
    static void Main(string[] args)
    {
        MainForm mainForm = new MainForm();

        FormShown Shown = new FormShown(mainForm);

        mainForm.Shown += new EventHandler(Shown.mainForm_Shown);

        mainForm.ShowDialog();
    }
}

class FormShown
{
    MainForm mainForm;

    public FormShown(MainForm aMainForm)
    {
        mainForm = aMainForm;
    }

    public void f1_Shown(object sender, EventArgs e)
    {
        mainForm.AddText("hello!");
    }
}

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();

        PictureBox.Image = MyApp.Properties.Resources.MyImage;
    }

    public void AddText(string text)
    {
        foreach (char c in text)
        {
            TextBox.Text += c;
            TextBox.Refresh();
            System.Threading.Thread.Sleep(100);
            TextBox.SelectionStart = TextBox.Text.Length;
        }
    }
}   

I'd hoped that setting the image in code from resources would be quick enough, and I expected the picturebox to be loaded by the Form.Shown event - am I wrong to think this?

I've tried setting the image in the design view as opposed to in code, but with the same results.

Is there a different event I should be using? I believe Shown is the last to be called.

Thanks!

Upvotes: 0

Views: 377

Answers (1)

Shell
Shell

Reputation: 6849

If you know the Windows Form Event life cycle then you can easily understand what problem exactly you are getting. Basically image and other controls will be drawn when form is being painted and the Paint event will be raised at the end. So, that means application will not draw any control or graphic until all process will not done.

You should call the AddText() method in different process.

Upvotes: 1

Related Questions