可以给窗体添加一个共有属性,或者共有方法,只要别个可以访问到的就行……
比如,Form2代码: public class Form2 : Form
{
public string ValueText { get; set; } private TextBox txt_Input; public Form2()
{
txt_Input = new TextBox();
txt_Input.Location = new Point(10, 10);
txt_Input.Size = new Size(100, 20);
txt_Input.TextChanged += new EventHandler(txt_Input_TextChanged); this.Controls.Add(txt_Input);
this.ClientSize = new Size(120, 40);
} private void txt_Input_TextChanged(object sender, EventArgs e)
{
this.ValueText = txt_Input.Text;
} }
在 Form1 中的按钮事件这样写
比如,Form2代码: public class Form2 : Form
{
public string ValueText { get; set; } private TextBox txt_Input; public Form2()
{
txt_Input = new TextBox();
txt_Input.Location = new Point(10, 10);
txt_Input.Size = new Size(100, 20);
txt_Input.TextChanged += new EventHandler(txt_Input_TextChanged); this.Controls.Add(txt_Input);
this.ClientSize = new Size(120, 40);
} private void txt_Input_TextChanged(object sender, EventArgs e)
{
this.ValueText = txt_Input.Text;
} }
在 Form1 中的按钮事件这样写
Form2 frm = new Form2();
frm.ShowDialog(this);
MessageBox.Show(frm.ValueText);
private void button1_Click(object sender, System.EventArgs e)
{
Form2 f2 = new Form2();
f2.Tag = this;
f2.Show();
}//定义一个公共方法用于修改Form1上textBox1的值
public void SetTextBox(string strValue)
{
this.textBox1.Text = strValue;
}
在Form2窗体中//按钮事件调用Form1中的SetTextBox方法来设置Form1中textBox1的值
private void button1_Click(object sender, System.EventArgs e)
{
Form1 f1 = (Form1)this.Tag;
f1.SetTextBox("123");
}
using System.Runtime.InteropServices;public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//声明 API 函数 [DllImport("User32.dll",EntryPoint="SendMessage")]
private static extern int SendMessage(
int hWnd, // handle to destination window
int Msg, // message
int wParam, // first message parameter
int lParam // second message parameter
);
[DllImport("User32.dll",EntryPoint="FindWindow")]
private static extern int FindWindow(string lpClassName,string lpWindowName);
//定义消息常数
public const int USER = 0x500;
public const int TEST = USER + 1;
//向窗体发送消息的函数[Page] private void SendMsgToMainForm(int MSG)
{
Form2 frm = new Form2();
frm.Show();
int WINDOW_HANDLER = FindWindow(null, @"Form2");
if(WINDOW_HANDLER == 0)
{
//throw new Exception("Could not find Main window!");
}
SendMessage(WINDOW_HANDLER,MSG,100,200);
} private void button1_Click(object sender, EventArgs e)
{
SendMsgToMainForm(USER);
} }
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
protected override void DefWndProc(ref System.Windows.Forms.Message m)
{
switch(m.Msg)
{//接收自定义消息 USER,并显示其参数
case Form1.USER:
string message = string.Format ("Received message!parameters are :{0},{1}",m.WParam ,m.LParam);
textBox1.Text = message;
break;
default:
base.DefWndProc(ref m); break;
}
}
}