从另一个对象访问Form组件将引发“未处理System.NullReferenceException”

问题描述

| 我正在尝试从WCF对象中修改属于Form2的TextBox。
namespace server2
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private ServiceHost duplex;

        private void Form2_Load(object sender,EventArgs e)     /// once the form loads,create and open a new ServiceEndpoint.
        {
            duplex = new ServiceHost(typeof(ServerClass));
            duplex.AddServiceEndpoint(typeof(IfaceClient2Server),new NetTcpBinding(),\"net.tcp://localhost:9080/service\");
            duplex.Open();
            this.Text = \"SERVER *on-line*\";
        }
    }


    class ServerClass : IfaceClient2Server
    {


        IfaceServer2Client callback;

        public ServerClass()
        {
            callback = OperationContext.Current.GetCallbackChannel<IfaceServer2Client>();

        }

        public void StartConnection(string name)
        {
            var myForm = Form.ActiveForm as Form2;
            myForm.textBox1.Text = \"Hello world!\";  /// <- this one trows “System.NullReferenceException was unhandled”
                                                    /// unless Form2 is selected when this fires.

            callback.Message_Server2Client(\"Welcome,\" + name );
        }


        public void Message_Cleint2Server(string msg)
        {
        }

        public void Message2Client(string msg)
        {
        }

    }




    [ServiceContract(Namespace = \"server\",CallbackContract = typeof(IfaceServer2Client),SessionMode = SessionMode.Required)]


    public interface IfaceClient2Server           ///// what comes from the client to the server.
    {
        [OperationContract(IsOneWay = true)]
        void StartConnection(string clientName);

        [OperationContract(IsOneWay = true)]
        void Message_Cleint2Server(string msg);
    }


    public interface IfaceServer2Client          ///// what goes from the sertver,to the client.
    {
        [OperationContract(IsOneWay = true)]
        void AcceptConnection();

        [OperationContract(IsOneWay = true)]
        void RejectConnection();

        [OperationContract(IsOneWay = true)]
        void Message_Server2Client(string msg);
    }

}
然而,\“ myForm.textBox1.Text = \” Hello world!\“; \”行引发了System.NullReferenceException未被处理\“ ... 任何想法,谢谢!     

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)