在 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 布尔值是否为真,如果是,请使用 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;
}
}