一 问题:
1 可不可以不使用线程?
可以。需要建立父窗口和子窗口之间的父子关系。
2 如何建立父子关系?
在子窗体中增加一个类型为父窗口的属性(即ChildFrm类中设置 public ParentFrm parentFrm{get;set;}属性)。
二 显示效果
三 代码
1 入口程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ParentFrm parentFrm = new ParentFrm();
Application.Run(parentFrm);//启动父窗体
}
}
}
2父窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class ParentFrm : Form
{
public ParentFrm()
{
InitializeComponent();
}
public TextBox GetTbParent()
{
return this.TbParent;//TbParent 是私有的对象 ,所以要有公有的方法获取TbParent对象
}
private void button1_Click(object sender, EventArgs e)//点击事件
{
ChildFrm childFrm = new ChildFrm();
childFrm.parentFrm = this; //建立父子关系
childFrm.Show();//显示子窗体
}
}
}
3 子窗体
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class ChildFrm : Form
{
public ParentFrm parentFrm{get;set;}
public ChildFrm()
{
InitializeComponent();
}
private void TbChild_TextChanged(object sender, EventArgs e)
{
parentFrm.GetTbParent().Text = this.TbChild.Text;//将用户输入到子窗体TEXTBOX控件中的内容放入到父窗体的TEXTBOX控件中
}
}
}