简体   繁体   English

按钮单击事件直到完成为止不更新文本框

[英]Button Click Event not updating textbox until Finished

Here's a C# code, What happens is when qsubmit button is clicked, program straight away displays "wait..!". 这是一个C#代码,发生的情况是单击qsubmit按钮时,程序立即显示“ wait ..!”。

When I debug the program it is found that when I click and function executes textbox1.text = "Hello"; 当我调试程序时,发现单击并函数执行textbox1.text = "Hello"; but doesn't updates textbox, it updates only when the control goes off the event function, when that happens value of textbox has already been changed to "wait..!" 但不会更新文本框,它仅在控件关闭事件功能时才更新,而当该事件发生时,文本框的值已更改为"wait..!" . I want to know why it doesn't updates textbox instantly(If that would have done, I would have seen the text during Thread.Sleep() ) 我想知道为什么它不能立即更新文本框(如果这样做,我会在Thread.Sleep()期间看到文本)

 private void Button_QSubmit_Click(object sender, EventArgs e)
 {
      textBox1.Text = "Hello";
      Thread.Sleep(1000);
      textBox1.Text = "Wait..!";  
 }

You are hanging the UI Thread by calling Thread.Sleep from the Main Thread (UI), to update the text box you have to let the UI thread do its job outside your function to update the UI..anyway call Application.DoEvents() before the sleep. 您正在通过从主线程(UI)调用Thread.Sleep来挂起UI线程,以更新文本框,您必须让UI线程在函数之外完成更新UI的工作。.始终调用Application.DoEvents()睡前 But calling Application.DoEvents() is a bad design 但是调用Application.DoEvents()是一个错误的设计

The UI thread is responsible to redraw the windows. UI线程负责重绘窗口。 So as long as you are doing this inside the UI Thread (eg a Button click event), the process is busy with your code and the window is not drawn. 因此, 只要您在UI线程中执行此操作(例如,按钮单击事件),该过程就会占用您的代码,并且不会绘制窗口。

A easy solution could be the use of an Timer. 一个简单的解决方案是使用计时器。 Just add an timer and in the button click you start it (eg you set itup to fire in 1 second). 只需添加一个计时器,然后在按钮中单击即可启动它(例如,将其设置为在1秒钟内触发)。

The Timer Event then will simply set the Text. 然后,计时器事件将简单地设置文本。

https://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx shows details about the Timer class. https://msdn.microsoft.com/zh-cn/library/system.windows.forms.timer.aspx显示有关Timer类的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM