I have a WinForms form with, amongst other things, a WebBrowser control. I use the browser to display a preview of the file the user creates.
When the user loads a document, I want it to automatically refresh the preview window to show the new document. This works 100%.
However, I just added a “Load most recent document” feature which, as you should be able to tell, loads the last document on program start up. Although it goes through the same code path as any other method of loading a document (Open button, File->Open, File->MRU, etc), the preview does not refresh on start up.
I’ve followed the execution in the debugger, and all the code is being executed. However, it appears that the WebBrowser simply isn’t working. If I hit the refresh button (which goes through the same code path) afterwards, it works fine.
public partial class frmMain : Form {
int scrolltop = 0, scrollleft = 0;
delegate void VoidDelegate();
private void Form1_Load(object sender, EventArgs e) {
//irrelevant initialization code omitted
//this is normally 'about:blank', but it doesn't matter anyway
html.Navigate("http://google.com");
NewFile();
if (GlobalSettings.MRU.Files.Count > 0) {
LoadFile(GlobalSettings.MRU.Files[0]);
}
}
public void NewFile() {
//misc blanking omitted
html.DocumentText = "";
}
private void LoadFile(string file) {
//file loading code omitted
//Trying to call RefreshPreview after everything else is done.
this.Invoke(new VoidDelegate(RefreshPreview));
//RefreshPreview());
}
public void RefreshPreview() {
//preserve the position if possible
if (html.Document.Body != null) {
scrolltop = html.Document.Body.ScrollTop;
scrollleft = html.Document.Body.ScrollLeft;
}
//string code = HtmlProcessing.ProcessCode(txtCode.Text, GetImageList());
string code = "If you can see this, it worked.";
html.DocumentText = code;
}
}
If you paste this code into a form named frmMain with a WebBrowser control named html, and hook up the Form1_Load event (note to self, rename this ;), you should be able to reproduce this sample. Maybe add a button that calls RefreshPreview() too.
So, short version: During Form_Load, WebBrowser doesn’t do anything. Afterwards, it works fine. I need it to do something during Form_Load, what am I doing wrong?
I would recommend moving your code to the Form.Shown event. The problem is likely due to the order and timing of Form events. Since Load occurs prior to display of the form, the WebBrowser’s VisibleChanged event never occurs, and I believe it is completely inactive.