【问题标题】:How to set webbrowser documenttext from another form?如何从另一个表单设置 webbrowser 文档文本?
【发布时间】:2014-08-30 19:32:02
【问题描述】:

我创建了一个简单的消息框来获取用户输入并将结果设置到以前形式的网络浏览器中。
这是我的MsgInput 源代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

public partial class MsgInput : Form
{
    private readonly Main mainForm;
    public string input_type;
    string script;

    public MsgInput()
    {
        this.mainForm = mainForm;
        InitializeComponent();
    }

    private void MsgInput_Load(object sender, EventArgs e)
    {
        if (input_type == "echo")
        {
            richTextBox1.Text = "Echo : void echo ( string $arg1 [, string $... ] )";

        }
    }

    private void btnOk_Click(object sender, EventArgs e)
    {
        if (input_type == "echo")
        {
            script = mainForm.webBrowser1.DocumentText;
            if (chkNewLine.Checked == true)
            {
                script += "\n";
            }
            script += "echo " + txtInput.Text;
            mainForm.webBrowser1.DocumentText = script;
            this.Close();
        }
    }
}

我没有在第一种形式中添加任何东西,只是将 webbrowser 修饰符设置为 public。
当我调试时。当我尝试提交文本时返回 null

Main表格

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

    namespace EasyPHP
    {
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void echoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var msg = new MsgInput();
            msg.input_type = "echo";
            msg.Show();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            webBrowser1.DocumentText = "<pre>";
        }

        private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {

        }
    }
}

【问题讨论】:

  • this.mainForm = mainForm; 将自己分配给它。您需要 mainform 的实例。将它传递给MsgInput 的构造函数。也不要给控件提供公共访问修饰符,你有一天会后悔的。而是在主窗体中添加一个名为 SetWebBrowserText 的方法并调用它(让主窗体自己设置文档文本)。
  • 以前我也很好奇为什么会有一个警告说Assignment made to same variable 我认为分配一个相同的变量是没用的。如果我更改修饰符会发生什么?

标签: c# winforms


【解决方案1】:

我假设你得到一个空引用异常。如果您发布主表单代码,它将很有用。据我了解,您应该传入主表单引用,这就是您获得空引用的原因。

在您的代码中,将构造函数更改如下(ParentForm 是您的父表单的类名)

public MsgInput(ParentForm mainForm)
        {
            this.mainForm = mainForm;
            InitializeComponent();
        }

在主窗体中

MsgInput frm = new MsgInput(this);
            frm.input_type = "echo";
            frm.Show(this);

否则请分享完整代码,我们可以快速提供帮助

【讨论】:

  • 我已经更新了我的问题并尝试您的解决方案。它的成功!谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多