C#如何实现等待界面上任意一个按钮按下再执行语句后面的操作呢,界面有5个按钮,要判断是那个按钮按下的

2025-01-05 15:56:55
推荐回答(2个)
回答1:

 public Form1()
        {
            InitializeComponent();

            Button bt1 = new Button();
            bt1.Click += new EventHandler(bt1_Click);

            Button bt2 = new Button();
            bt2.Click += new EventHandler(bt2_Click);

            Button bt3 = new Button();
            bt3.Click += new EventHandler(bt3_Click);

            Button bt4 = new Button();
            bt4.Click += new EventHandler(bt4_Click);

            Button bt5 = new Button();
            bt5.Click += new EventHandler(bt5_Click);

            Button bt_start = new Button();
            bt_start.Click += new EventHandler(bt_start_Click);
        }
        /// 
        /// 按下了某个按钮
        /// 

        /// 
        /// 
        private void button1_Click(object sender, EventArgs e)
        {
            bt2_Click(sender,e);//换5个按钮单击试试
        }
        /// 
        /// 开始等待按下某个按钮
        /// 

        /// 
        /// 
        void bt_start_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(a =>
            {
                while (flag == 0)
                {
                    //等待按钮单击事件发生
                    Thread.Sleep(200);
                }
                Invoke((EventHandler)delegate {
                    switch (flag)
                    {
                        case 1:
                            MessageBox.Show("单击了按钮1");
                            break;
                        case 2:
                            MessageBox.Show("单击了按钮2");
                            break;
                        case 3:
                            MessageBox.Show("单击了按钮3");
                            break;
                        case 4:
                            MessageBox.Show("单击了按钮4");
                            break;
                        case 5:
                            MessageBox.Show("单击了按钮5");
                            break;
                    }
                });
                flag = 0;
            }, null);
        }

        int flag = 0;
        void bt5_Click(object sender, EventArgs e)
        {
            flag = 5;
        }

        void bt4_Click(object sender, EventArgs e)
        {
            flag = 4;
        }

        void bt3_Click(object sender, EventArgs e)
        {
            flag = 3;
        }

        void bt2_Click(object sender, EventArgs e)
        {
            flag = 2;
        }

        void bt1_Click(object sender, EventArgs e)
        {
            flag = 1;
        }

回答2:

让5个按钮指向同一事件。在事件中判断事件源。也就是那个所谓的sender会标识是哪个按钮触发的。