我正在尝试创建一个程序,在输入的时间(小时,分钟和秒)后关闭计算机。一切正常,除非它根本不更新richTextBox1。请有人帮忙解决这个问题。提前谢谢。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
namespace ShutdownPC
{
public partial class Form1 : Form
{
public int inputHours = 0;
public int inputMinutes = 0;
public int inputSeconds = 0;
public int totalSeconds = 0;
public int totalMilliseconds = 0;
public int ticks = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Enabled = false;
textBox2.Enabled = false;
textBox3.Enabled = false;
button1.Enabled = false;
// Hours
if (!string.IsNullOrWhiteSpace(textBox1.Text))
{
inputHours = int.Parse(textBox1.Text);
}
// Minutes
if (!string.IsNullOrWhiteSpace(textBox2.Text))
{
inputMinutes = int.Parse(textBox2.Text);
}
// Seconds
if (!string.IsNullOrWhiteSpace(textBox3.Text))
{
inputSeconds = int.Parse(textBox3.Text);
}
// Updating richTextBox1 every second with remaining time left
totalSeconds = (inputHours * 3600) + (inputMinutes * 60) + inputSeconds;
timer1.Start();
while (ticks < totalSeconds)
{
TimeSpan time = TimeSpan.FromSeconds(totalSeconds);
string timeOutput = time.ToString(@"hh\:mm\:ss");
richTextBox1.AppendText(String.Format(timeOutput));
Thread.Sleep(1000);
richTextBox1.Clear();
}
// Shutting down computer
totalMilliseconds = ((inputHours * 3600) + (inputMinutes * 60) + inputSeconds) * 1000;
Thread.Sleep(totalMilliseconds);
richTextBox1.AppendText("end");
//Process.Start("shutdown", "/s /t 0");
}
private void timer1_Tick(object sender, EventArgs e)
{
ticks++;
}
}
}
答案 0 :(得分:1)
正如SLaks所说,如果您阻止UI线程,该框将永远不会更新,但在.net中您有等待/异步,只需将您的方法转换为private async void button1_Click
而不是Thread.Sleep
使用{ {1}}。
另外,您可以使用
设置框内容await Task.Delay
这应该是
TimeSpan time = TimeSpan.FromSeconds(totalSeconds);
richTextBox1.AppendText(String.Format(timeOutput));
如果你想要倒计时。