[英]How to disable textbox while another thread is running
我想在线程运行时禁用文本框。 线程执行完成后,应启用表单上的文本框。
码
Thread thread = new Thread(new ThreadStart(ScannerThreadFunction));
thread.Start();
public void ScannerThreadFunction()
{
try
{
Scan();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
}
}
在Scan()运行之前,应禁用TextBox。 scan()完成后,我想启用TextBox。
在WPF中,您可以在扫描方法期间执行此操作。 您只需将TextBox的启用和禁用推送到UI线程,然后您就像调度程序一样执行此操作:
private void button1_Click(object sender, RoutedEventArgs e)
{
var thread = new Thread(new ThreadStart(ScannerThreadFunction));
thread.Start();
}
public void ScannerThreadFunction()
{
try
{
Scan();
}
catch (Exception ex)
{
//Writing to the console won't be so useful on a desktop app
//Console.WriteLine(ex.Message);
}
finally
{
}
}
private void Scan()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(() => MyTextbox.IsEnabled = false));
//do the scan
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal,
new Action(() => MyTextbox.IsEnabled = true));
}
在WinForms中,您也可以在扫描方法中执行此操作,但执行方式略有不同。 您需要检查表单上的InvokeRequired布尔值是否为true,如果是,请使用MethodInvoker,如下所示:
private void button1_Click(object sender, EventArgs e)
{
var thread = new Thread(new ThreadStart(ScannerThreadFunction));
thread.Start();
}
public void ScannerThreadFunction()
{
try
{
Scan();
}
catch (Exception ex)
{
//Writing to the console won't be so useful on a desktop app
//Console.WriteLine(ex.Message);
}
finally
{
}
}
private void Scan()
{
ChangeTextBoxIsEnabled(false);
//do scan
ChangeTextBoxIsEnabled(true);
}
private void ChangeTextBoxIsEnabled(bool isEnabled)
{
if (InvokeRequired)
{
Invoke((MethodInvoker)(() => MyTextbox.Enabled = isEnabled));
}
else
{
MyTextbox.Enabled = isEnabled;
}
}
在启动后台线程之前 - 禁用文本框。 在后台线程中,在处理完成时通知主线程(如果您正在使用WPF,请使用主线程的Dispatcher
),并在主线程中再次启用文本框。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.