EventLoop for WinForm

   abstract class EventLoop
    {
        protected static bool mExit = false;
        protected static int mCode = 0;
        protected static EventLoop mImpl;

        public static void Register(EventLoop impl) { mImpl = impl; }
        public static void Exit(int code) { mExit = true; mCode = code; }

        public abstract int Run();

        public static int Start()
        {
            if (mImpl != null)
                return mImpl.Run();
            return 0;
        }
    }

    class EventLoopImpl : EventLoop
    {
        System.Windows.Forms.Timer mTimer = new System.Windows.Forms.Timer();

        public override int Run()
        {
            mTimer.Tick += new EventHandler(TimerEventProcessor);

            mTimer.Interval = 1000;
            mTimer.Start();
            mExit = false;
            while (!mExit)
            {
                Application.DoEvents();
            }

            return mCode;
        }

        private void TimerEventProcessor(object sender, EventArgs e)
        {
            mTimer.Stop();
            if (mExit == false)
            {
                mTimer.Enabled = true;
            }
        }
    }

 

使用方法:

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            EventLoop.Register(new EventLoopImpl());
        }
        private void button1_Click(object sender, EventArgs e)
        {
            EventLoop.Exit(0);
        }

        private void commandToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.listView1.Items.Add("Step 1");
            EventLoop.Start();
            this.listView1.Items.Add("Step 2");
            EventLoop.Start();
            this.listView1.Items.Add("End");

        }
    }

 

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