C# | 在已有的两个窗体之间传值

项目下共有两个窗体:主窗体 Form1,子窗体 imgView。

要实现的是在Form1上点击按钮,打开imgView,将主窗体已经打开的BitMap的对象传递到子窗体中,并且显示。

Form1和imgView继承自Form:

Form1:

public partial class Form1 : Form

imgView:

public partial class imgView : Form

在Form1下建立公共对象:

public partial class Form1 : Form
    {
        public Bitmap bitMap;
        public Form1()
        {
            InitializeComponent();
        }
     ...
     }

imgView窗体代码:

public partial class imgView : Form
    {
        Bitmap bitMap;
        public imgView(Bitmap m)
        {
            InitializeComponent();
            bitMap = m;
        }

        private void imgView_Load(object sender, EventArgs e)
        {
            this.BackgroundImage = bitMap;
        }
    }

点击Form1上的button新建窗体实例化imgView:

 private void button1_Click(object sender, EventArgs e)
        {
            if(bitMap==null)
            {
                MessageBox.Show("Image doesn't exist!");
                return;
            }
            imgView frm = new imgView(bitMap);
            frm.Show();
        }

你可能感兴趣的:(C#)