C#窗体互动

说白了就是在一个窗体操作另外一个窗体的东西。

原理是把form2的数据提取出来,利用中间的静态类middle来传递数据,触发事件,调用委托,来修正form1

效果如下:

1

 

Form1.cs

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 FormInteractive
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Middle.sendEvent += new Middle.SendMessage(this.DoMethod);
        }

        public void DoMethod(string getstr)
        {
            listBox1.Items.Add(getstr);
        }


        private void button1_Click(object sender, EventArgs e)
        {
            Form2 c = new Form2();
            c.Show();
        }
    }
}

Middle.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FormInteractive
{
    /// <summary>
    /// 这是一个静态类,用于定义委托和事件已经调用事件
    /// </summary>
    public static class Middle
    {
        public delegate void SendMessage(string str);

        public static event SendMessage sendEvent;

        public static void DoSendMessage(string str)
        {
            sendEvent(str);
        }

    }
}

Form2.cs

 

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 FormInteractive
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //调用Middle类中的DoSendMessage
            Middle.DoSendMessage(textBox1.Text);
            textBox1.Text = ""; //将textBox1清空
            textBox1.Focus();   //将鼠标锁定在textBox1
        }
    }
}
posted on 2013-11-10 13:27  神秘藏宝室  阅读(390)  评论(0编辑  收藏  举报

 >>>转载请注明出处<<<