winform跨窗体操作

一、构造方法实现

窗体一:
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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()  
        {  
            InitializeComponent();  
        }  
       
        public void f_Change()//改变页面状态的方法,用于给form2调用  
        {  
            this.BackColor = Color.LightBlue;
            btnform1.Enabled = false;
        }

        

        private void btnform1_Click(object sender, EventArgs e)
        {

            Form2 f2 = new Form2(this);//在构造函数中传递当前页面对象
            f2.Show();  

        }  
    }
}

窗体二:
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 WindowsFormsApplication1
{

    public partial class Form2 : Form
    {
        //实例化一个form1对象
        Form1 new_f1 = new Form1();
       
        public Form2()
        {
            InitializeComponent();
        }

        //重载构造方法,接form1传来的form1对象
        public Form2(Form1 f1)
        {
            new_f1 = f1;
            InitializeComponent();
        
        }
     
        private void btnform2_Click(object sender, EventArgs e)
        {
          
            new_f1.f_Change();//此时操作new_f1就相当于操作form1

        }
       
      
    }
}


二、委托事件实现

窗体一:

using System;
using System.Drawing;
using System.Windows.Forms;

namespace 跨窗体调用控件
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.ChangeColor += new ChangeFormColor(f_ChangeColor);
f.Show();
}
void f_ChangeColor(bool topmost)
{
this.BackColor = Color.LightBlue;
this.Text = "改变成功";
}
}
}

 

窗体二:

using System;
using System.Windows.Forms;

namespace 跨窗体调用控件
{
public delegate void ChangeFormColor(bool topmost);
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
public event ChangeFormColor ChangeColor;
private void button1_Click(object sender, EventArgs e)
{
ChangeColor(true);//执行委托实例
}
}
}

posted @ 2013-04-17 15:51  yuchao.xia  阅读(389)  评论(0编辑  收藏  举报