在Form_Load期间,WebBrowser控件不响应

时间:2011-03-04 20:57:15

标签: c# events .net-3.5 webbrowser-control

我有一个WinForms表单,其中包括一个WebBrowser控件。我使用浏览器显示用户创建的文件的预览。

当用户加载文档时,我希望它自动刷新预览窗口以显示新文档。这100%工作。

但是,我刚刚添加了一个“加载最新文档”功能,正如您应该知道的那样,它会在程序启动时加载最后一个文档。虽然它与任何其他加载文档的方法(打开按钮,文件 - >打开,文件 - > MRU等)通过相同的代码路径,但预览在启动时不会刷新。

我已经跟着调试器中的执行,并且正在执行所有代码。但是,似乎WebBrowser根本不起作用。如果我之后点击刷新按钮(通过相同的代码路径),它可以正常工作。

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;
    }
}

如果您将此代码粘贴到名为frmMain且名为html的WebBrowser控件的表单中,并挂钩Form1_Load事件(请注意自我,重命名为;),您应该能够重现这个样本。也许添加一个调用RefreshPreview()的按钮。

所以,简短版本:在Form_Load期间,WebBrowser不做任何事情。之后,它运作正常。我需要它在Form_Load期间做一些事情,我做错了什么?

1 个答案:

答案 0 :(得分:2)

我建议您将代码移至Form.Shown事件。问题可能是order and timing of Form events引起的。由于Load在显示表单之前发生,因此WebBrowser的VisibleChanged事件永远不会发生,我相信它完全不活动。

相关问题