两界面的数据传递是通过定义 static string来确定的。
一端:Form1
public static string str1; // 在Form1 中定义
另一端:Form2
label = Form1.str1; //在Form2 中实现,数据的传递
Form1
:
using System.Threading;
namespace shuju
{
public partial class Form1 : Form
{
Thread thread;
public delegate void hua(); // 定义委托
public static string str1;
public Form1()
{
InitializeComponent();
Form2 frm = new Form2(); //打开另一界面
frm.Show();
thread = new Thread(new ThreadStart(thread_str)); // 创建线程
thread.Start();
}
public void thread_str()
{
while(true)
{
bbbb();
}
}
public void bbbb()
{
try
{
if (label1.InvokeRequired)
{
hua ff = new hua(bbbb);
this.Invoke(ff);
}
else
{
label1.Text = Form2.str2;
}
}
catch (Exception e)
{
thread.Abort();
MessageBox.Show(e.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
str1 = textBox1.Text;
textBox1.Text = "";
}
private void button3_Click(object sender, EventArgs e)
{
//label1.Text = Form2.str2;
}
}
}

Form2:
using System.Threading;
namespace shuju
{
public partial class Form2 : Form
{
public delegate void bian(); //定义委托
Thread thread;
public static string str2;
public Form2()
{
InitializeComponent();
thread = new Thread(new ThreadStart(threading)); //线程
thread.Start();
}
public void threading()
{
while (true)
{
Setting();
}
}
public void Setting() // 刷新 label
{
try
{
if (this.label1.InvokeRequired)
{
bian fc = new bian(Setting);
this.Invoke(fc);
}
else
{
label1.Text = Form1.str1;
}
}
catch(Exception e)
{
thread.Abort();
MessageBox.Show(e.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = Form1.str1;
}
private void button2_Click(object sender, EventArgs e)
{
str2 = textBox1.Text;
}
}
}
这篇博客探讨了如何在C#的两个不同界面之间进行数据传递。通过定义静态变量`str1`,Form1和Form2可以共享数据。在Form1中创建线程并使用委托`hua`更新Label文本,而Form2使用类似的线程和委托`bian`进行数据同步。当按钮被点击时,数据会从输入框传递到相应的静态变量,从而在界面上实时更新。

3005

被折叠的 条评论
为什么被折叠?



