且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用不可见的 System.Windows.Forms.WebBrowser?

更新时间:2023-02-08 17:00:31

要防止窗口显示,请将此代码粘贴到您的表单中:

To prevent the window from being shown, paste this code into your form:

    protected override void SetVisibleCore(bool value) {
        if (!this.IsHandleCreated) {
            CreateHandle();
            value = false;
        }
        base.SetVisibleCore(value);
    }

请注意,Load 事件在您明确使表单可见之前不会运行,因此请移动您在 if 语句中获得的任何代码.

Beware that the Load event won't run until you explicitly make your form visible so move any code you've got there inside the if statement.

未运行 DocumentCompleted 事件通常是由于未运行消息循环 (Application.Run) 造成的.WebBrowser 需要一个线程和一个标记为 [STAThread] 的线程,以便触发其事件.消息循环对于 COM 组件非常重要.

Not getting the DocumentCompleted event to run is usually caused by not running a message loop (Application.Run). WebBrowser requires one, and a thread that's marked with [STAThread], in order to fire its events. The message loop is very important for COM components.

防止隐形形式偷取焦点也很重要,代码如下:

Is it also important to prevent the invisible form from stealing focus, with the code below:

protected override bool ShowWithoutActivation
{
    get { return true; } // prevents form creation from stealing focus
}

form1.Enabled = false; // prevents inner controls from stealing focus