C# 多线程

来源:互联网 发布:英语口语外教网络教学 编辑:程序博客网 时间:2024/04/30 21:29

老师叫我们预习多线程,最后要求我们做一个打字游戏.

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

        Yield makeLetter;//声明产生字母的对象
        Label lab;//声明标签的对象
        Move move;//声明移动对象
        Random rd;//随机数对象

        //timer事件
        private void timer1_Tick(object sender, EventArgs e)
        {
            makeLetter = new Yield();//实例化产生字母的对象
            rd = new Random();
            lab = new Label();//实例化lab对象
            lab.Size = new Size(20,20);
            lab.BackColor = Color.Blue;
            lab.TextAlign = ContentAlignment.MiddleCenter;
            lab.Font = new System.Drawing.Font("Arial", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            lab.Text = makeLetter.YieldLetter();//设置标题的名称
            lab.Left = rd.Next(10, (this.Width) - 10);//设置出现的位置
            this.Controls.Add(lab);//把lab添加到指定容器
           
            //执行往下掉的线程
            move = new Move(lab, this);//实例化移动类
            Thread obj = new Thread(new ThreadStart(move.MoveLetter));
            obj.Start();
        }

        private void frmMain_KeyPress(object sender, KeyPressEventArgs e)
        {
            foreach (Label lab in this.Controls)
            {
                if (lab is Label)
                {
                    if (lab == null)
                    {
                        break;
                    }

                    if (e.KeyChar == char.Parse(lab.Text))
                    {

                        lab.Dispose();
                        this.Controls.Remove(lab);

                    }
                }
            }
        }
    }
}

可是自己在在窗体里面丢了一个button,就不能打字了连frmMain_KeyPress都进入不了.这是为什么