how to start and show a window?

  • Thread starter Thread starter DBC User
  • Start date Start date
D

DBC User

Hi,
I have windows form program. While that form is building to show, I
want to show another window (kinda splash screen so I can show the user
the program is loading..)
Can someone suggest a good approach?
I did the following at present and is not working.

In the main form (CAB project) right before base.run(), I started a
seperate thread and launched a windows form and it did show up (in the
task bar not the window though) and closes immediatly.

Is there something I need to know how to show a window in a seperate
thread?

Thanks.
 
What you describe should work; are you perhaps using .Show() to display
the form? If so, the second thread will reach the end of it's
ThreadStart method, and will terminate, tearing down the form. The way
to handle this is, for instance, to call ShowDialog() on the splash
form (so that it remains open), and then (when ready) ask the splash
form to close itself (ending that thread).

Here's a handy wrapper for all of this using generics and
IDisposable... just replace <MySplashForm> with <YourForm>...

class MySplashForm : Form {
public MySplashForm() {
Text = "I'm a splash form";
FormBorderStyle = FormBorderStyle.FixedDialog;
ShowInTaskbar = MinimizeBox = MaximizeBox = false;
}
}
static void Main() {
using (Splash<MySplashForm> loader = new
Splash<MySplashForm>()) {
Thread.Sleep(10000);
}
MessageBox.Show("That do?");
}
class Splash<T> : IDisposable where T : Form, new() {
T _form;
public Splash() {
Thread thread = new Thread(Show);
thread.IsBackground = true;
thread.Start();
}
private void Show() {
_form = new T();
using (T form = _form) {
form.ShowDialog();
} // to ensure disposed on exit
}
private void Close() {
try { _form.Close(); } catch { } // swallow
}
public void Dispose() {
if (_form != null) {
try { _form.Invoke((MethodInvoker) this.Close); } catch
{ } // swallow
_form = null;
}
}
}
 
Forgot to say; the Thread.Sleep(10000) represents your code loading;
you might choose to dispose of the loader in the Load event of your
form, although it can be simpler if you simply wrap an "Initialize"
form method with the splash code.

also - you can use the alternative "using" syntax (without a variable):

using (new Splash<MySplashForm>()) {
Thread.Sleep(10000);
}

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top