I have a small problem, when I open a new window in WPF like so:
private void button2_Click(object sender, RoutedEventArgs e)
{
var newWindow = new Main();
newWindow.Show();
}
If I try to use Application.Current.Shutdown(); at the end of it my entire application shuts down rather than just my first initial window. So my question would be is there a way to open a new window while closing the previous window safely?
Thanks :)
I'd do something like this:
//Somewhere in your class
YourOtherForm otherForm = null;
//then, on the event handler
private void button2_Click(object sender, RoutedEventArgs e) {
if((otherForm.IsDisposed) || (null == otherForm)) {
otherForm = new YourOtherForm();
// or, this is an MDI or something
// otherForm = new YourOtherForm(this);
// assuming you have an extra constructor to pass the parent
}
otherForm.Show();
this.Close(); // or this.Hide(); if it's the main form
}
Edit: I haven't tested this code tho..
The only way to do this is to run the program externally (I will find the code to do this shortly). Otherwise, anything that is created from within the main application will be destroyed when the parent shuts down.
The code to spin up a new program:
System.Diagnostics.Process.Start("program.exe");
You will need to change the ShutdownMode to OnLastWindowClose in your App.xaml.
Related
I want to be able to press a button and have the program open up a new window and close the old one.
I have followed solutions from this link but i have never has success with any of them How do I open a second window from the first window in WPF?
Here is my work soo far:
Window editor = new Window();
editor.Show();
this.Close();
But this does nothing.
The program should open up a new window and close the old one.
The functionality you described will work just fine. The Problem there is would more likely be the function or Methode in which you call this function.
To write a Methode that would handle a Button press as you want is pretty good described here: https://www.c-sharpcorner.com/forums/c-sharp-button-click-hold-and-release.
Hopefully, this will help you otherwise just ask
here is a small Implementation if that helps:
public partial class MainWindow : Window
{
private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
Window editor = new MainWindow();
editor.Show();
this.Close();
}
private void MainWindow_KeyUP(object sender, KeyEventArgs e)
{
}
public MainWindow()
{
this.KeyDown += MainWindow_KeyDown;
this.KeyUp += MainWindow_KeyUP;
}
}
You have to call the second window from the first. This is something I did for a project where it popped up a new login panel window:
private void displayLoginPanel_Click(object sender, EventArgs e)
{
LoginPanel myLogin = new LoginPanel(this);
myLogin.Show();
this.Hide();
}
I used hide() instead of close() because you can see that I am sending a reference of the parent to the child LoginPanel in order to come back later. You can replace the Hide() with Close().
I'm fairly new at C#, and have spent the whole day to find a soultion to this to address the issue I'm having so apologies if this is simple, or has been wlsewhere! I have two Forms, Main and Config. Main loads, and has a button to open the Config form and then hide itself as so:
private void btnConfig_Click(object sender, EventArgs e)
{
Config config = new Config();
config.Show();
this.Visible = false;
}
It works just fine and the Config form opens. The Config from has two buttons (a Save and a Close button). In essence, both buttons have the same end effect, close the Config form and re-show the Main form, coded as so:
private void btnClose_Click(object sender, EventArgs e)
{
this.Hide();
Main main = new Main();
main.Visible = true;
}
The issue is that if I close the Config screen using the 'cross', Config is 'closed' but Main is not displayed and the programcontinues to run. I've tried using OnFormClosing and got stuck in an awful loop! The Cross should do the same as the Save/Close buttons, hide the Config form and open Main again.
If you want to show the config Form and reshow the Main form when the config has changed you normally would want something as a Config Form to show Modal.
To show a Modal Form, you'll to use ShowDialog(). ShowDialog() is also a blocking call, which gives you the ability to pick up where you left of.
In the mainform:
private void btnConfig_Click(object sender, EventArgs e)
{
var config = new Config();
this.Visible = false;
// this call blocks!
var dialogResult = config.ShowDialog();
// when the configform is closed, the code resumes here
this.Visible = true;
}
This also gives you the possibitlity, to cancel the config form, by setting
DialogResult property of the Config form to DialogResult.Cancel just before closing.
I'm not too sure what you're looking for exactly but this is how I would go about it.
Change your function to the following and have a private Config object under your main form class.
private Config config;
private void btnConfig_Click(object sender, EventArgs e)
{
if(config==null || config.IsDisposed)
{
config = new Config(this); // Pass the main form into the constructor of config
}
config.ShowDialog();
this.Visible = false;
}
Create a constructor (for Config) that takes in the main form as a parameter and have the main form as a private object. This allows you to show the original form as apposed to just creating a new one every time.
private Form mainForm;
public Config(Form main)
{
mainForm = main;
}
And change your close action.
private void btnClose_Click(object sender, EventArgs e)
{
this.Hide();
mainForm.Visible = true;
}
I have been stuck with this for some time now. I can't open a new form on button click.
If i create and .Show() form in the start form constructor i will work. I dont get it! :-(
StartUp Form
public Form1()
{
InitializeComponent();
startmessage();
br = Logic.loadXML("theshiiiiiittt.xml");
br2 = br.Clone();
loadboxes();
//serializeTest();
t = new Thread(contactDBUpdate);
//t.IsBackground = true;
t.Start();
}
Button event:
private void resultButton_Click(object sender, EventArgs e)
{
ResultForm rf = new ResultForm(this);
rf.Show();
this.Enabled = false;
}
Hope this is enough.
In my case it was caused by the fact that i wanted to make my forms non-modal. So i changed them from form.ShowDialog(parentForm) to form.Show().
But that caused the ObjectDisposedException if i try to show a form a second time because somewhere in the code was this.Close();. Form.Close also disposes it.
MSDN:
When a form is closed, all resources created within the object are
closed and the form is disposed.
I just needed to change
this.Close();
to
this.Hide();
Found my code problem.
I took one more look at the Stack trace and found i a message "Icon".
this.Icon.Dispose();
Startupform had this line.
This code fixed my problem:
private void resultButton_Click(object sender, EventArgs e)
{
ResultForm rf = new ResultForm(this);
rf.Icon = this.Icon;
rf.Show();
this.Enabled = false;
}
Thanks for the helping hands...
The problem is that your form object loose the scope and is disposed off.
If you want to keep the dialog open, use Form.ShowDialog();
Try this:
private void resultButton_Click(object sender, EventArgs e)
{
using(ResultForm rf = new ResultForm(this))
{
rf.ShowDialog();
}
this.Enabled = false;
}
Wile Implementing singleton pattern on windows form I got this error too.
The solution is that you have to assign a null value to the static reference in
protected override void Dispose(bool disposing)
by putting simple line.
obj=null; //obj is the static reference in the class.
Being a very first user in Windows Form Development I want to ask a simple question ...
I created a form(MainWindow.cs) within the solution which opens at the time of running that solution.
Latter I created a second form(SecondWindow.cs) and created a event so that it can be called from the first window by clicking a button.When the second window loded up the first window(MainWindow.cs) will be disabled.
Now I want to enable the MainWindow.cs when the second window is closed.
How to do That...
A simple solution I already have is to hide the MainWindow.cs and latter on closing the second window make a new object of first window and show it.But it is not a good way i think because there is already a object created by .net framework for first window automatically, so why we should create a new object of Mainwindow.cs .
Code Of First Window ( MainWindow.cs ) :
private void priceControllToolStripMenuItem_Click(object sender, EventArgs e)
{
SecondWindow price = new SecondWindow();
this.Enabled = false;
price.Show();
}
Code Of Second Window ( On closing SecondWindow.cs )
private void price_controll_FormClosed(object sender, FormClosedEventArgs e)
{
// what will goes here to make the MainWindow.cs to enable state
}
Use price.ShowDialog() to show second form as modal dialog. Main form will be disabled until you close second form:
private void priceControllToolStripMenuItem_Click(object sender, EventArgs e)
{
using(SecondWindow price = new SecondWindow())
price.ShowDialog();
}
You can pass the main form as an owner to the second form
private void priceControllToolStripMenuItem_Click(object sender, EventArgs e)
{
SecondWindow price = new SecondWindow() { Owner = this };
this.Enabled = false;
price.Show();
}
Then you can reference it from the second form.
private void price_controll_FormClosed(object sender, FormClosedEventArgs e)
{
Owner.Enabled = true;
}
I have a WinForm that I create that shows a prompt with a button. This is a custom WinForm view, as a message box dialog was not sufficient.
I have a background worker started and running. I also want to exit the while(aBackgroundWorker.IsBusy) loop if the button on myForm was clicked.
//MyProgram.cs
using(CustomForm myForm = new CustomForm())
{
myForm.Show(theFormOwner);
myForm.Refresh();
while(aBackgroundWorker.IsBusy)
{
Thread.Sleep(1);
Application.DoEvents();
}
}
Right now, in the CustomForm the Button_clicked event, I have
//CustomForm.cs
private void theButton_Click(object sender, EventArgs e)
{
this.Close();
}
Do I need to add more code to the CustomForm class, or the location where I declare and initialize the form in order to be able to detect a closure?
To detect when the form is actually closed, you need to hook the FormClosed event:
this.FormClosed += new FormClosedEventHandler(Form1_FormClosed);
void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// Do something
}
Alternatively:
using(CustomForm myForm = new CustomForm())
{
myForm.FormClosed += new FormClosedEventHandler(MyForm_FormClosed);
...
}
void MyForm_FormClosed(object sender, FormClosedEventArgs e)
{
// Do something
}
You might be going overkill. To show a form like a dialog window and wait for it to exit before returning control back to the calling form, just use:
mySubForm.ShowDialog();
This will "block" the main form until the child is closed.
Make sure your background worker supports cancellation and as others have pointed out use the form closed event handler. This code should point you in the right direction:
using(CustomForm myForm = new CustomForm())
{
myForm.FormClosed += new FormClosedEventHandler(ChildFormClosed);
myForm.Show(theFormOwner);
myForm.Refresh();
while(aBackgroundWorker.IsBusy)
{
Thread.Sleep(1);
Application.DoEvents();
}
}
void ChildFormClosed(object sender, FormClosedEventArgs e)
{
aBackgroundWorker.CancelAsync();
}
Handle the FormClosing event of the form to be notified when the form is closing, so you can perform any cleanup.
You should be able to hook into the FormClosing and FormClosed events.
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosed.aspx
Closing is before it's closed.
Closed is after it's closed.
A couple things...
First, it appears that loop is there in order to prevent execution form proceeding while the dialog is open. If that is the case, change you .Show(parent) to .ShowDialog(parent). That will also take care of the rest of your question.
Note that this.Hide(); is not the same as this.Close(); in the actual dialog your overriding the closed event