Right now I have C# code to spawn a new window in a different thread, this works, but as soon as the new spawned window opens, it closes and the thread ends. How would I mak
For a project I'm working on I created a form that'll pop up, stay open while the task is running and close afterwards.
It contains one ProgressBar with the following settings:
progressBar1.Style=ProgressBarStyles.Marquee
progressBar1.MarqueeAnimationSpeed =
<-- set your custom speed in miliseconds hereIf you want to, you can set the form's TopMost
property to true
.
Here is the code for the form:
public partial class BusyForm : Form
{
public BusyForm(string text = "Busy performing action ...")
{
InitializeComponent();
this.Text = text;
this.ControlBox = false;
}
public void Start()
{
System.Threading.Tasks.Task.Run(() =>
{
this.ShowDialog();
});
}
public void Stop()
{
BeginInvoke((Action)delegate { this.Close(); });
}
public void ChangeText(string newText)
{
BeginInvoke((Action)delegate { this.Text = newText; });
}
}
And here is the code to use the form in your code:
BusyForm busyForm = new BusyForm(text: "Opening database ...");
busyForm.Start();
//do your stuff here
busyForm.Stop();
UPDATE: I ran into some underlying troubles with the threading. Here is an updated version of the code. For some background info, this form has a progress bar that is shown when a task is busy. I added the ChangeText
command to show an example of how you can interact with this form from another form. Should probably also mention that your Main
in Program.cs
should have the [STAThread]
attribute as seen below.
[STAThread]
static void Main(string[] args)
{
System.Globalization.CultureInfo.DefaultThreadCurrentCulture = System.Globalization.CultureInfo.InvariantCulture;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}