Code Snippet
public class SampleButton : System.Windows.Forms.Button
{
private sealed class WaitForm : System.Windows.Forms.Form
{
private readonly StringFormat textFormat = new StringFormat();
public WaitForm()
{
this.textFormat.Alignment = StringAlignment.Center;
this.textFormat.LineAlignment = StringAlignment.Center;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
e.Graphics.DrawString("Please wait...", this.Font, SystemBrushes.ControlText, this.ClientRectangle, this.textFormat);
}
protected override void OnHandleDestroyed(EventArgs e)
{
base.OnHandleDestroyed(e);
this.textFormat.Dispose();
}
}
private static readonly object EventButtonClick = new object();
private readonly WinTimer timer = new WinTimer();
private volatile bool busying;
private bool showWaitForm;
private WaitForm waitingForm;
public SampleButton()
{
this.timer.Tick += delegate
{
if (this.busying)
{
if (this.waitingForm == null)
{
this.waitingForm = new WaitForm();
this.waitingForm.ShowDialog(this.FindForm());
}
}
else
{
if (this.waitingForm != null)
{
this.timer.Stop();
this.waitingForm.Close();
this.waitingForm.Dispose();
this.waitingForm = null;
}
}
};
this.timer.Interval = 2000;
}
public bool ShowWaitForm
{
get { return this.showWaitForm; }
set { this.showWaitForm = value; }
}
public event EventHandler ButtonClick
{
add { this.Events.AddHandler(EventButtonClick, value); }
remove { this.Events.RemoveHandler(EventButtonClick, value); }
}
protected virtual void OnButtonClick(EventArgs e)
{
if (this.busying) return;
EventHandler handler = (EventHandler)this.Events[EventButtonClick];
if (handler != null)
{
this.busying = true;
if (this.showWaitForm)
{
this.timer.Start();
Thread thread = new Thread(new ThreadStart(delegate
{
try
{
handler(this, e);
}
finally
{
this.busying = false;
}
}));
thread.Start();
}
else
{
handler(this, e);
this.busying = false;
}
}
}
protected override void OnClick(EventArgs e)
{
base.OnClick(e);
OnButtonClick(e);
}
protected override void OnHandleDestroyed(EventArgs e)
{
base.OnHandleDestroyed(e);
this.timer.Dispose();
}
}
new System.EventHandler(this.longTimeButton_ButtonClick);
void longTimeButton_ButtonClick(object sender, EventArgs e)
{
Thread.Sleep(10000);
Hello Wei Zhou,
Thanks for your answer!
I must tell that I will analyse your code very carefully, but what I can see on a first glance is that you have created a new control with an especial event. That´s very cool, but one of my intentions is not to replace the existing buttons on my application, based on the fact that it will consume a lot of time and resources (this is a really big application).
I'll think more deeply in your solution, and post you anything shortly.
Thank you again.