日期:2014-05-20  浏览次数:20829 次

高分求助:委托与多线程刷新窗体控件后操作方法
//从服务端接收到待生成的TextBox个数
string   recvString= " ";  

//Form_Load()
{

                        Thread   thread   =   new   Thread(new   ThreadStart(targett));
                        thread.Start();

}


public   delegate   void   MyInvoke(string   str);         //str   即为接收到的字符串


private   void   targett()
{
                        while   (bb)             //bb=true;
                        {
                                Byte[]   bbb   =   new   Byte[1024];
                                string   aa   =   " ";
                                int   bytes;
                                bytes   =   sock.Receive(bbb,   bbb.Length,   0);
                                aa   +=   System.Text.Encoding.Default.GetString(bbb,   0,   bytes);

                                recvString   +=   aa;

                                //使用委托传值给新建窗体
                                MyInvoke   myIn   =   new   MyInvoke(CreateNewForm);
                                this.BeginInvoke(myIn,   new   object[]   {   recvString   });
                        }
}

//刷新当前窗体,根据传入的字符串生成新窗体

public   CreateNewForm(String   str)
{
this.Controls.Clear();

int   Num=Convert.ToInt32(str);   //转化为数字

                  TextBox   []tb=new   TextBox[Num];
                for(int   i=0;i <Num;i++)
{
tb[i].Name= "TextBox "+i.ToString();
tb[i].Location   =   new   Point(100,10*i+10);
tb[i].TabIndex   =   i;

this.Controls.Add(tb[i]);

}


this.Activate();   //激活当前窗体为主窗体
tb[0].Focus();   //第一个TextBox获取焦点
}
------------------------
问题:

VS2005下;以上操作可以正常接收刷新当前窗体,并激活当前窗体,但是无论如何获取到的第一个TextBox无法获取输入焦点,通过在窗体上点击鼠标才可以!

在网上搜索结果说是委托不能对新窗体操作,不知道到怎么回事,请高手赐教!

------解决方案--------------------
for(int i=0;i <Num;i++)
{
tb[i]=new TextBox(); //加入这一句
tb[i].Name= "TextBox "+i.ToString();
tb[i].Location = new Point(100,10*i+10);