Skip to content

Instantly share code, notes, and snippets.

@JonHaywood
Created September 11, 2012 21:21
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save JonHaywood/3702171 to your computer and use it in GitHub Desktop.
Save JonHaywood/3702171 to your computer and use it in GitHub Desktop.
Wait Dialog for Windows Forms
private void ShowWaitDialog(Action codeToRun)
{
ManualResetEvent dialogLoadedFlag = new ManualResetEvent(false);
// open the dialog on a new thread so that the dialog window gets
// drawn. otherwise our long running code will run and the dialog
// window never renders.
(new Thread(() =>
{
Form waitDialog = new Form()
{
Name = "WaitForm",
Text = "Please Wait...",
ControlBox = false,
FormBorderStyle = FormBorderStyle.FixedDialog,
StartPosition = FormStartPosition.CenterParent,
Width = 240,
Height = 50,
Enabled = true
};
ProgressBar ScrollingBar = new ProgressBar()
{
Style = ProgressBarStyle.Marquee,
Parent = waitDialog,
Dock = DockStyle.Fill,
Enabled = true
};
waitDialog.Load += new EventHandler((x, y) =>
{
dialogLoadedFlag.Set();
});
waitDialog.Shown += new EventHandler((x, y) =>
{
// note: if codeToRun function takes a while it will
// block this dialog thread and the loading indicator won't draw
// so launch it too in a different thread
(new Thread(() =>
{
codeToRun();
// after that code completes, kill the wait dialog which will unblock
// the main thread
this.Invoke((MethodInvoker)(() => waitDialog.Close()));
})).Start();
});
this.Invoke((MethodInvoker)(() => waitDialog.ShowDialog(this)));
})).Start();
while (dialogLoadedFlag.WaitOne(100, true) == false)
Application.DoEvents(); // note: this will block the main thread once the wait dialog shows
}
@evanbross
Copy link

Is there an easy way to add an elapsed timer to this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment