分別建立Form 1和Form 2。
Form1 原碼
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- namespace GlobalData_FormToForm
- {
- public struct Global //全域變數
- {
- public static byte g_Counter;
- }
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- Global.g_Counter = 0;
- }
- private void button1_Click(object sender, EventArgs e)
- {
- Global.g_Counter++;
- lbl_Msg.Text = Global.g_Counter.ToString();
- }
- private void button2_Click(object sender, EventArgs e)
- {
- Form2 frm_2 = new Form2();
- frm_2.Tag = this;
- frm_2.Show();
- }
- }
- }
Form2 原碼
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- namespace GlobalData_FormToForm
- {
- public partial class Form2 : Form
- {
- public Form2()
- {
- InitializeComponent();
- Form1 frm_1 = (Form1)this.Tag;
- }
- private void button1_Click(object sender, EventArgs e)
- {
- Global.g_Counter++;
- lbl_Msg.Text = Global.g_Counter.ToString();
- }
- }
- }
好了,現在可以按Form1 button 和 Form2 button,變數值相互累加,是不是很簡單 ^-^
重要的地方就是this.Tag 及 public struct Globa 不能放在class Form裡哦~~
執行結果:
3個Form也行,再多也無所謂。
建立Form 3(原碼和Form2 一樣)
- using System.Data;
- using System.Drawing;
- using System.Text;
- using System.Windows.Forms;
- namespace GlobalData_FormToForm
- {
- public partial class Form3 : Form
- {
- public Form3()
- {
- InitializeComponent();
- Form1 frm_1 = (Form1)this.Tag;
- }
- private void button1_Click(object sender, EventArgs e)
- {
- Global.g_Counter++;
- lbl_Msg.Text = Global.g_Counter.ToString();
- }
- }
- }
Form 1稍做修改
- private void button2_Click(object sender, EventArgs e)
- {
- Form2 frm_2 = new Form2();
- frm_2.Tag = this;
- frm_2.Show();
- }
改成
- private void button2_Click(object sender, EventArgs e)
- {
- Form2 frm_2 = new Form2();
- frm_2.Tag = this;
- frm_2.Show();
- Form3 frm_3 = new Form3();
-
- frm_3.Tag = this;
- frm_3.Show();
- }
執行結果: