这是我的问题......我正在创建一个私人消息系统。我有主窗体(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的新实例,而实例已经存在。但我不知道如何访问这个“现有实例”。你有经验丰富的程序员有什么建议吗?
由于
EDIT(添加发送方法) - 位于Form1
public delegate void _sendPM(string Send_Message);
public void sendPM(string Send_Message)
{
Server_Send("PM|" + Send_Message);
}
答案 0 :(得分: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
}
}