跨線程安全調用Windows 窗體控件

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        private delegate void showMessage(string msg);
        showMessage show;

        public Form1()
        {
            InitializeComponent();
            show = new showMessage(Methrod1);
        }

        public void doit1()
        {
            textBox1.Invoke(show, "OK!");
        }

        public void doit2()
        {
            try
            {
                textBox1.Text = "OK!";
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        public void Methrod1(string text)
        {
            textBox1.Text = text ;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Methrod1("OK!");
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(doit1));
            thread.Start();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
        }

        private void button4_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(new ThreadStart(doit2));
            thread.Start();

        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章