请问高手线程中如何打开一个Form?如我的网络读线程,当读到一个数据后,我要在Form中显示,发现在一个建立的form上用show()不行.分不够还可加

解决方案 »

  1.   

    你这样操作肯定是不行的,思路是关于界面显示的操作必须在ui线程执行,
    所以你在另一线程的显示form 的操作必须发送至ui线程,具体用委托实现,
    详细过程网上一搜 就有了。
      

  2.   

    参看
    http://blog.csdn.net/knight94/archive/2006/03/16/626584.aspx
      

  3.   

    这是我写的一个示例:using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using SIO = System.IO;
    using ST = System.Threading;namespace WindowsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                DisplayDataHandler += new DisplayDataDelegate(DisplayDataM);
            }        private void button1_Click(object sender, EventArgs e)
            {
                ST.Thread readThread = new System.Threading.Thread(new System.Threading.ThreadStart(ReadData));
                readThread.Start();
            }        private delegate void DisplayDataDelegate();
            private DisplayDataDelegate DisplayDataHandler;        private void ReadData()
            {
                SIO.StreamReader sr = new System.IO.StreamReader("test.txt");
                while (sr.Peek() > 0)
                {
                    string str = sr.ReadLine();
                    if (str.Contains("yang"))
                    {
                        DisplayData();
                        break;
                    }
                }
                sr.Close();
            }        private void DisplayData()
            {
                BeginInvoke(DisplayDataHandler);
            }        private void DisplayDataM()
            {
                this.label1.Text = "yang";
            }
        }
    }
      

  4.   

    //首先写一个网络读对象
    class reader
    {
    //定义委托
    public delegate void handler(可以有参数);
    public event handler mhandler ;
    //在网络读线程里触发这个事件
    if(mhandler != null)
    {
    mhandler ();//如果有参数加上参数
    }
    }
    //在主线程里实例化网络读对象:
    reader r = new reader()
    //同时定义事件
    r.mhandler += new reader.handler(aa)
    //定义一个委托来调用invoke方法
    public delegate void voidDelegate ();
    //编写方法 aa
    private void aa()
    {
    voidDelegate bb = new voidDelegate(cc)
    this.invoke(bb);
    }
    //实现方法cc
    private void cc()
    {
    //在这里弹出你的窗体
    }
      

  5.   

    你有主窗口吗,如果有的话,如下:
    private yourForm myDataForm = null;
    public void ShowForm()
    {
       if( myDataForm != null )
          myDataForm = new yourForm();
       myDataForm.Show();
    }//In your thread function
    // Show a window
    MethodInvoker mi = new MethodInvoker( this.ShowForm );// "this"  is your current main form
    this.BeginInvoke( mi );
      

  6.   

    不要在独立线程中创建UI元素,
    可以这样来设计,
    处理逻辑可以在独立的线程上,对处理结果的显示还通过在UI线程上建立窗体来显示,两者的通信可以通过异步委托来实现。
      

  7.   

    CSDN真好,好心人多。谢谢高手