日期:2014-05-17  浏览次数:20867 次

坐等回复:C#跨窗体操作控件,求详细代码改错
C# code

窗口1 的代码
namespace HistoryGame
{

    public delegate void CloseForm();  

    public partial class FrmSuspend : Form
    {
        

        public FrmSuspend()
        {
            InitializeComponent();
        }
        public event CloseForm FrmSuspendClose;  

        public void picContinue_Click(object sender, EventArgs e)
        {
            FrmSuspendClose();
        }
窗体2
namespace HistoryGame
{
    public partial class FrmSuspendCopy : Form
    {
        public FrmSuspendCopy()
        {
            InitializeComponent();
        }

        FrmSuspend frc = new FrmSuspend();

        void CloseBySuspend(bool topmost)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void FrmSuspendCopy_Load(object sender, EventArgs e)
        {
        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            frc.FrmSuspendClose += new CloseForm(CloseBySuspend);
        }
    }
}

为什么窗体1单击后出现
 FrmSuspendClose(); 未进行实例化。的错误,请问什么情况。



我要实现的效果是从窗口1的按钮单击后调用窗体2(CloseBySuspend)的方法,请问有没有更好的方案,求方案。

------解决方案--------------------
可以直接实例化调用就行了
public void picContinue_Click(object sender, EventArgs e)
{
FrmSuspendCopy frm2=new FrmSuspendCopy();
frm2.CloseBySuspend(true);
}
------解决方案--------------------
你那2个窗体看起来没任何关联


你上面的代码2个窗体还没关联,虽然在FrmSuspendCopy中实例了FrmSuspend窗体,但是没有加载
frc.FrmSuspendClose += new CloseForm(CloseBySuspend);

C# code


namespace HistoryGame
{
    public partial class FrmSuspendCopy : Form
    {
        public FrmSuspendCopy()
        {
            InitializeComponent();
        }

        FrmSuspend frc = new FrmSuspend();

        void CloseBySuspend(bool topmost)
        {
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void FrmSuspendCopy_Load(object sender, EventArgs e)
        {
          frc.FrmSuspendClose += new CloseForm(CloseBySuspend);
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
         
        }
    }
}

------解决方案--------------------
窗体 1中 FrmSuspendClose () 实例在哪? //就是这个frc.FrmSuspendClose += new CloseForm(CloseBySuspend);

void CloseBySuspend(bool topmost)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
这个改成 public 然后在 窗体1中 绑定到 FrmSuspendClose 上