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 かどうかを確認する必要があります。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;
}
}