2012-11-27 140 views
1

在用C#编写的Windows窗体应用程序中单击按钮后,如何等待另一个按钮被点击?同时我正在通过当前信息动态更新datagridview。如何等待按钮被点击?

编辑

按钮1被点击后,我要反复更新当前信息的dataGridView,并点击按钮2时,我想停止更新的dataGridView。

+0

目前尚不清楚,您的意思是*等待另一个按钮被点击* ...您的意思是禁用除该按钮之外的窗体上的所有用户输入?或者是什么? – horgh

+0

就像它说的那么简单。假设按钮1被点击,我希望程序等待另一个按钮被点击。一旦button1被点击,我想动态更新dataGridView。它不断更新,直到按下按钮2。 –

+2

如果它像说的那么简单,人们就不会问清楚了......按钮有点击事件处理程序,它们只有在被点击时才会执行。所以实际上该程序是“等待按钮被点击”。 – ryadavilli

回答

4

使用Timer Class

public partial class Form1 : Form 
{ 
    System.Windows.Forms.Timer timer; 

    public Form1() 
    { 
     InitializeComponent(); 

     //create it 
     timer = new Timer(); 
     // set the interval, so it'll fire every 1 sec. (1000 ms) 
     timer.Interval = 1000; 
     // bind an event handler 
     timer.Tick += new EventHandler(timer_Tick); 

     //... 
    } 

    void timer_Tick(object sender, EventArgs e) 
    { 
     //do what you need 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     timer.Start(); //start the timer 
     // switch buttons 
     button1.Enabled = false; 
     button2.Enabled = true;   
    } 

    private void button2_Click(object sender, EventArgs e) 
    { 
     timer.Stop(); //stop the timer 
     // switch buttons back 
     button1.Enabled = true; 
     button2.Enabled = false; 
    } 

从MSDN:

A定时器被用来提高在用户定义的时间间隔的事件。这个 Windows计时器专为线程用于执行处理的单线程环境而设计。它要求用户代码 有一个UI消息泵可用,并始终从相同的 线程运行,或将呼叫编组到另一个线程。

当使用此计时器,使用Tick事件来执行轮询 操作或为的 指定的一段时间显示一个初始屏幕。每当Enabled属性设置为true且属性间隔大于零时,将根据Interval属性设置以间隔 引发Tick事件。

+0

服务我的目的。非常感谢你。再次抱歉给您带来不便。 –

+0

@ soham.m17您一定会受到欢迎......不便之处在于OP不想回应评论......这里没关系 – horgh

0

所以你有按钮A和按钮B.当按钮A被按下时,你想等待按钮B被按下,然后做一些特别的事情?没有更多的信息的最简单的方法是这样的:

private void OnButtonAClicked(object sender, EventArgs e) 
{ 
    ButtonA.Enabled = false; 
    ButtonA.Click -= OnButtonAClicked; 
    ButtonB.Click += OnButtonBClicked; 
    ButtonB.Enabled = true; 
} 

private void OnButtonBClicked(object sender, EventArgs e) 
{ 
    ButtonB.Enabled = false; 
    ButtonB.Click -= OnButtonBClicked; 

    // Do something truly special here 

    ButtonA.Click += OnButtonAClicked; 
    ButtonA.Enabled = true; 
} 

该代码将切换(初始状态;按键A被启用,按钮B被禁用),当按下按钮A,按钮B被激活并处理事件等。