读书人

c#父窗体控制子窗体的有关问题

发布时间: 2013-03-28 10:20:24 作者: rapoo

c#父窗体控制子窗体的问题
有4个form,form1,form2,form3,form4,
form1是父窗体有四个按钮button1,button2,button3,,button4
点击button2,在form1的panel1里面出现form2;
点击button3,在form1的panel1里面出现form3;
点击button4,在form1的panel1里面出现form4;
点击button1,在form2,form3,form4的picturebox1里出现image1
重点是,再次按button2,button3,button4时出现相应的from2,form3,form4,且各form的picturebox1内均有图片image1
[解决办法]
new Form,设置parent为panel,toplevel=false
窗体间传值参考http://www.cnblogs.com/cosoft/archive/2011/08/08/2130659.html
[解决办法]
随便写了下,有点乱,但是应该能实现你的要求


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();
}

private void button1_Click(object sender, EventArgs e)
{
FormCollection collection = Application.OpenForms;
foreach (Form form in collection)
{
if (form.Name == "Form2")
{
((Form2)form).SetImage();
form.Select();
}
else if (form.Name == "Form3")
{
((Form3)form).SetImage();
form.Select();
}
else if (form.Name == "Form4")
{
((Form4)form).SetImage();
form.Select();
}


}
}

private void button2_Click(object sender, EventArgs e)
{
if (!GetFormIsOpen("Form2"))
{
Form2 form2 = new Form2();
form2.TopLevel = false;
panel1.Controls.Add(form2);
form2.Show();
}
}

private void button3_Click(object sender, EventArgs e)
{
if (!GetFormIsOpen("Form3"))
{
Form3 form3 = new Form3();
form3.TopLevel = false;
panel1.Controls.Add(form3);
form3.Show();
}
}

private void button4_Click(object sender, EventArgs e)
{
if (!GetFormIsOpen("Form4"))
{
Form4 form4 = new Form4();
form4.TopLevel = false;
panel1.Controls.Add(form4);
form4.Show();
}
}

private bool GetFormIsOpen(string formName)
{
bool result = false;

FormCollection forms = Application.OpenForms;
foreach (Form frm in forms)
{
if (frm.Name == formName)
{


Control[] control = panel1.Controls.Find(formName, false);
if (control != null && control.Length > 0)
{
control[0].BringToFront();
}
result = true;
break;
}
}

return result;
}
}
}



然后分别在Form2、Form3、Form4中加入公开方法:

public void SetImage()
{
this.pictureBox1.Image = Image.FromFile(@"C:\Users\Public\Pictures\Sample Pictures\back.png");
}

读书人网 >C#

热点推荐