this.Close(); doesn't work in window wpf - c#

In wpf, window I am calling window forms. Before calling that I just want to close that window. Here is my code.
public partial class MainWindow : MetroWindow
{
public MainWindow()
{
InitializeComponent();
}
private void BtnIntroClick(object sender, RoutedEventArgs e)
{
PdfReader form = new PdfReader(1);
form.ShowDialog();
this.Close();
}
}
No error, but form is not closing.
And in window form also, this.Close() in not working
public partial class PdfReader : Form
{
public PdfReader(int page_num)
{
InitializeComponent();
var executingFolder = System.AppDomain.CurrentDomain.BaseDirectory;
var dbPath = System.IO.Path.Combine(executingFolder, "BiodermaProduct.pdf");
axAcroPDF1.LoadFile(dbPath);
axAcroPDF1.setCurrentPage(page_num);
}
private void PdfReader_FormClosed(object sender, FormClosedEventArgs e)
{
this.Opacity = 0;
MainWindow w = new MainWindow();
w.ShowDialog();
}
}

It will close when you close your PdfReader form. Form.ShowDialog returns only when the form is closed. So this.Close() is not called until ShowDialog finishes.
What you can do is set this.Visibility = Visibility.Hidden before calling form.ShowDialog();

Important detail that we need to bear in mind when we deal with windows closure and other UI operation: we need to execute it in UI thread only.
This is exactly that happened in my case.
I raised an event from the server and when it happened I raised another event through custom Event Aggregator to close the second Window that is opened (without shutting down the application).
However it didn't happen without an error or visible reason. My window was still opened.
Nevertheless, when I enabled "Common Language Runtime exception" through visual studio settings:
I caught the exception: "Full Exception: System.InvalidOperationException: The calling thread cannot access this object because a different thread owns it.
at System.Windows.Threading.Dispatcher.VerifyAccess()
at System.Windows.Window.Close().........."
Consequently, instead of this:
ServiceLocator.Current.GetInstance<IEventAggregator>().GetEvent<ServerDisconnectedEvent>()
.Subscribe(e => Close());
Run this:
ServiceLocator.Current.GetInstance<IEventAggregator>().GetEvent<ServerDisconnectedEvent>()
.Subscribe(e => Application.Current.Dispatcher.BeginInvoke(new Action(Close)));
I hope this will safe time for someone like me :)

If you read this MSDN article you'll see that ShowDialog only returns when said window is closed. This means your code is blocked on that line until the window is closed. You have to close your current window first, then ShowDialog.
private void BtnIntroClick(object sender, RoutedEventArgs e)
{
PdfReader form = new PdfReader(1);
this.Close();
form.ShowDialog();
}
Note that Show does not work in this way.

When You use Window.ShowDialog(), it calls new Window modally, meaning you cannot go to the parent form.
The Window.Show() function shows the form in a non modal form. This means that you can click on the parent form.
However, this code will close your application as MSDN says(thanks to #Empereur Aiman):
A ShutdownMode of OnMainWindowClose causes Windows Presentation
Foundation (WPF) to implicitly call Shutdown when the MainWindow
closes, even if other windows are currently open.
And you should set your ShutdownMode to OnLastWindowClose as MSDN says:
If you set ShutdownMode to OnLastWindowClose, Windows Presentation
Foundation (WPF) implicitly calls Shutdown when the last window in an
application closes, even if any currently instantiated windows are set
as the main window (see MainWindow).
Just reorder your call of ShowDialog():
PdfReader form = new PdfReader(1);
this.Close();
form.ShowDialog();
or:
PdfReader form = new PdfReader(1);
form.Show();
this.Close();
and set ShutdownMode="OnLastWindowClose" at App.xaml file of your application:
<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml"
ShutdownMode="OnLastWindowClose"
>
</Application>
You code is:
PdfReader form = new PdfReader(1);
form.ShowDialog();
this.Close();
It means CLR executes modally your new PdfReader window. That is, execution of your program goes to PdfReader window. And only after closing PdfReader window, CLR executes your next row:
this.Close();
and your MainWindow() will be closed.

You need to change the order between this.Close(); & form.ShowDialog(); and it will work well
Try this code:
private void BtnIntroClick(object sender, RoutedEventArgs e)
{
PdfReader form = new PdfReader(1);
this.Close();
form.ShowDialog();
}

Related

How Do I Call Another Window With Button Press?

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().

how to open a form from another form in c#

i am writing a code for serial key registration.
if the serial key entered by the user is correct then anothr form must open and the present form must close.
please go thought the code.
namespace ExtTrigger
{
public partial class Activation : Form
{
public Activation()
{
InitializeComponent();
}
private void ActivateButton_Click(object sender, EventArgs e)
{
String key;
key = string.Concat(textBox1.Text,textBox2.Text,textBox3.Text,textBox4.Text);
if (key == "1234123412341234")
{
Properties.Settings.Default.Registered = true;
MessageBox.Show("hurray", "", MessageBoxButtons.OK);
Form1 f1= new Form1();
f1.ShowDialog();
this.Close();
}
else
MessageBox.Show("No Match", "", MessageBoxButtons.OK);
}
private void Activation_Load(object sender, EventArgs e)
{
}
}
my problem is: On clicking on ActivateBotton, Form1 opens but the present form doesnot close.
i have read in few threads that in VB we can change the property: ShutdownMode.
How can we do that in c#?
f1.ShowDialog(); blocks the call, it doesn't go to the next line until that new form has been closed.
An option would be to use:
f1.Show();
Show doesn't block the call, it passes to the next statement. It will not wait for the new form to be closed.
since you have show the second form as f1.ShowDialog() so first one remain open untile second one close, try this
Form1 f1= new Form1();
f1.Show();
this.Close();
The following code should do the trick:
using(Form1 f1 = new Form1())
{
this.Hide();
DialogResult result = f1.ShowDialog();
if(result == DialogResult.OK)
{
this.Show();
}
}
You create your new form within the using-block, then you hide your main form(or the form you are in at the moment) create a DialogResult that gets set by the newly opened form and open this form. Now you can set the results you want to check for inside of your new form and if everything went well inside of you new form you set the DialogResult to OK via:
this.DialogResult = DialogResult.OK;
Now back in our first form you check for the DialogResult and if it is okay you show your main form again. If it was not okay you could just reopen the 2nd form and let the user try again.
Opening a new form is very simple, but the way you do it really depends on your need.
Case 1: I would like to freeze/ block the calling form on secondary form call
In this case you should be using secondaryFormObj.ShowDialog();
Of course, when using this technique your called form, which now acts as a dialog, should "return" an answer to its caller parent on closure.
For example:
private void SecondaryForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Just a dummy code example.
// Always returns Yes result on form closure
this.DialogResult = System.Windows.Forms.DialogResult.Yes;
}
For more help and examples on this manner you can use MSDN:
DialogResult - MSDN
Case 2: I would like to have both forms responding at the same time
In this case you basically need to call secondaryFormObj.Show();
If you want the caller form to be hidden on secondary form call, just
invoke this.Hide();
after the call to secondaryFormObj.Show(); in the caller class.
You can also close the caller form using this.Close(); as long as the caller form is not the application's main form.
... And remember
Always make sure you initialized the secondary form object before
invoking it with either secondaryFormObj.Show(); or
secondaryFormObj.ShowDialog();
Initializing a form is done the same way like every typical object using the
new operator.
For example: secondaryFormObj = new Form();
Hopes this helps. Happy coding!

opening a window form from another form programmatically

I am making a Windows Forms application. I have a form. I want to open a new form at run time from the original form on a button click. And then close this new form (after 2,3 sec) programatically but from a thread other than gui main thread.
Can anybody guide me how to do it ?
Will the new form affect or hinder the things going on in the original main form ? (if yes than how to stop it ?)
To open from with button click please add the following code in the button event handler
var m = new Form1();
m.Show();
Here Form1 is the name of the form which you want to open.
Also to close the current form, you may use
this.close();
I would do it like this:
var form2 = new Form2();
form2.Show();
and to close current form I would use
this.Hide(); instead of
this.close();
check out this Youtube channel link for easy start-up tutorials you might find it helpful if u are a beginner
This is an old question, but answering for gathering knowledge.
We have an original form with a button to show the new form.
The code for the button click is below
private void button1_Click(object sender, EventArgs e)
{
New_Form new_Form = new New_Form();
new_Form.Show();
}
Now when click is made, New Form is shown. Since, you want to hide after 2 seconds we are adding a onload event to the new form designer
this.Load += new System.EventHandler(this.OnPageLoad);
This OnPageLoad function runs when that form is loaded
In NewForm.cs ,
public partial class New_Form : Form
{
private Timer formClosingTimer;
private void OnPageLoad(object sender, EventArgs e)
{
formClosingTimer = new Timer(); // Creating a new timer
formClosingTimer.Tick += new EventHandler(CloseForm); // Defining tick event to invoke after a time period
formClosingTimer.Interval = 2000; // Time Interval in miliseconds
formClosingTimer.Start(); // Starting a timer
}
private void CloseForm(object sender, EventArgs e)
{
formClosingTimer.Stop(); // Stoping timer. If we dont stop, function will be triggered in regular intervals
this.Close(); // Closing the current form
}
}
In this new form , a timer is used to invoke a method which closes that form.
Here is the new form which automatically closes after 2 seconds, we will be able operate on both the forms where no interference between those two forms.
For your knowledge,
form.close() will free the memory and we can never interact with that form again
form.hide() will just hide the form, where the code part can still run
For more details about timer refer this link, https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.7.2
You just need to use Dispatcher to perform graphical operation from a thread other then UI thread. I don't think that this will affect behavior of the main form. This may help you :
Accessing UI Control from BackgroundWorker Thread
This might also help:
void ButtQuitClick(object sender, EventArgs e)
{
QuitWin form = new QuitWin();
form.Show();
}
Change ButtQuit to your button name and also change QuitWin to the name of the form that you made.
When the button is clicked it will open another window, you will need to make another form and a button on your main form for it to work.
private void btnchangerate_Click(object sender, EventArgs e)
{
this.Hide(); //current form will hide
Form1 fm = new Form1(); //another form will open
fm.Show();
}
on click btn current form will hide and new form will open

a way to open a new window while closing the previous window

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.

How to show a status dialog while parent form is closing

I have a WPF app that takes a while to close so I want to add a 'please wait' dialog to show up while the main form is closing. However, when I added 'formmessage.show' to my main form's closing event handler, the form displays but instead of the 'please wait' text, all i get is a white rectangle. This only seems to happen when calling this code from the closing handler. It works fine from other handlers (form click or maximize). Can anyone help? Here is my simplified code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Form1 f = new Form1();
f.Show();
System.Threading.Thread.Sleep(3000);
}
}
Form1 has a label on it which says 'please wait'.
Try out:
Application.Current.Dispatcher.Invoke(
DispatcherPriority.Normal,
new Action(() =>
{
Form1 f = new Form1();
f.Show();
System.Threading.Thread.Sleep(3000);
}));
BTW, you can remove Thread.Sleep() because default value of the Application Shutdown mode is OnLastWindowClose so Application will be active until an user explicitly close active window, this behaviour could be changed by switching Application.ShutdownMode to OnMainWindowClose in the App.xaml file)
That would be because of the fact your creating the form in the same thread your telling to sleep, during which it's not going to respond to draw requests, try launching the form in another thread, and closing it in MainWindow's destructor.

Categories

Resources