public partial class Form1 : Form
{
private Point _defaultLocation;
private Thread _trd;
private delegate void MoveTextBoxDelegate();
private volatile bool _canceled = false;
public Form1()
{
InitializeComponent();
this._defaultLocation = this.textBox1.Location;
}
private void button1_Click(object sender, EventArgs e)
{
//既に移動処理中か?
if (this._trd != null && this._trd.IsAlive)
{
//移動処理を途中で終わらす
//this._trd.Abort(); //意図した動きをしないため使用しない
this._canceled = true;
this._trd.Join(); //!!! Application.DoEventsで止まっているためデッドロック発生 !!!
this._canceled = false;
}
//移動処理用スレッドをスタートする
this._trd = new Thread(MoveTextBoxWorker);
this._trd.IsBackground = true;
this._trd.Start();
}
private void MoveTextBoxWorker()
{
this.Invoke(new MoveTextBoxDelegate(MoveTextBox));
}
/// <summary>
/// 移動処理メソッド
/// </summary>
private void MoveTextBox()
{
Int32 moveDistance = 1;
this.textBox1.Location = this._defaultLocation;
while (this.textBox1.Location.X <= this.Width)
{
this.textBox1.Location = new Point(this.textBox1.Location.X + moveDistance, this.textBox1.Location.Y);
this.textBox1.Update();
moveDistance = moveDistance * 2;
Thread.Sleep(100);
Application.DoEvents(); //途中でもbutton1_Clickイベントを割り込ますため
if (this._canceled)
{
break;
}
}
}
/// <summary>
/// デバッグ用の情報が入っているtextBox1のTextをクリアする。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
this.textBox1.Clear();
}
}