3

这是我的问题...我正在创建一个私人消息系统。我有主表单(Form1)和私人消息屏幕(pm_screen),当我打开私人消息屏幕时,我希望将数据从这个表单发送回原来的。但是不知道怎么写。这是私人消息屏幕上 btnSend 事件的代码。

Message_Send = txtSend.Text.Trim();

Form1 frm1 = new Form1();
Invoke(new Form1._sendPM(frm1.sendPM), Message_Send);

当我尝试这个时,它返回一个错误,指出:

Object reference not set to an instance of an object

或类似的规定。我的猜测是,这是因为我正在启动 Form1 的新实例,而实例已经存在。但我不知道如何访问这个“现有实例”。你对更有经验的程序员有什么建议吗?

谢谢

编辑(添加发送方法) - 位于 Form1

public delegate void _sendPM(string Send_Message);
    public void sendPM(string Send_Message)
    {
        Server_Send("PM|" + Send_Message);
    }
4

1 回答 1

1

删除了我之前的答案,因为它处理了症状而不是实际问题。您需要将代码结构重做如下:

//Btw should be PmScreen or something else that follows naming conventions
public partial class pm_screen : Form  
{
    Form1 parentForm;

    public pm_screen(Form1 parentForm)
    {
        this.parentForm = parentForm;
    }

    //Write GUI code for the class here...

    public void acceptMessageFromParent(string message)
    {
        //Do stuff with string message
    }

    private void sendMessageToParent(string message)
    {
        parentForm.acceptMessageFromPrivate(message);
    }
}

public partial class Form1 : Form
{
    private void createPrivateMessageForm()
    {
        pm_screen privateScreen = new pm_screen(this);
        //You might want to store privateScreen in a List here, so you can
        //have several pm_screen instances per Form1
    }

    private void sendMessageToPrivate(pm_screen privateScreen, string message)
    {
        privateScreen.acceptMessageFromParent(message);
    }

    public void acceptMessageFromPrivate(string message)
    {
        //Do stuff with string message
    }
}
于 2013-09-21T05:20:05.377 回答