I have login window. From this login window, i am intializing the main window.
Once login successfully happened, i close the login window.
Now i am having two other windows, which i am calling from Main Window.
Once i close the main Window, I am able to close the other two windows as well as Main Window.
But program still runs in memory. I have to close it manually from the Visual Studio.
How should i close the Program all instances fully??
This is the Main window Close Event code.
private void usimClose(object sender, EventArgs e)
{
newScreen2.Close();
newScreen3.Close();
this.Close();
}
This is my Login Window Code. Once the user click on the submit button.
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
if (txtUserName.Text.Length == 0)
{
errormessage.Text = "Please Enter UserName";
txtUserName.Focus();
}
else
{
LoginStatus _status = _Login.LoginUsimgClient(txtUserName.Text, txtPassword.Password.ToString());
if (_status.BoolLoginstatus)
{
mainWindow.RunApplication();
string struserName = _status.StringUserFirstName;
mainWindow.userName.Text = "Welcome " + struserName;
mainWindow.Show();
this.Close();
}
else
{
errormessage.Text = _status.StringErrorDescription;
txtUserName.Text = String.Empty;
txtPassword.Password = String.Empty;
}
}
}
Try Application.Current.Shutdown();
From MSDN
Calling Shutdown explicitly causes an application to shut down,
regardless of the ShutdownMode setting. However, if ShutdownMode is
set to OnExplicitShutdown, you must call Shutdown to shut down an
application.
Important note
When Shutdown is called, the application will shut down irrespective
of whether the Closing event of any open windows is canceled.
This method can be called only from the thread that created the
Application object.
You can close all windows using this
App.Current.Shutdown();
or
you can manually close it
Window parentwin = Window.GetWindow();
parentwin.Close();
If you starting point is your MainWindow, then just start there.
Firstly, host the LoginForm in your MainWindow, and show it using ShowDialog() to force the user to interact with the LoginForm. Return the result of a successful/unsuccessful interaction to the MainForm.
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
var form = new LoginForm();
var result = form.ShowDialog();
if (result ?? false)
{
// Carry on opening up other windows
}
else
{
// Show some kind of error message to the user and shut down
}
}
Otherwise, technically your LoginForm is hosting your MainForm which is, frankly, odd.
Have a look at my answer here: How to close wpf window from another project
An Application.Current.Shutdown() will stop the application in a very abrupt way.
It is better to gracefully keep track of the windows and close them.
Related
Hey there StackOverflow community!
So I've been working on an application that checks if the user has entered valid credentials in a Login() form, then it switches over to an Intro_Sequence() form (where a .mp4 file is played in fullscreen mode) as a sort of aesthetic addition to the app. So far so good, no problems whatsoever.
The problem comes right after the Intro ends, where supposedly the application should switch over to a third form, called Main().
I have implemented a check whenever Windows Media Player (aka axWMPLib) changes its PlayState to see whether it has finished the playback.
If it has, then the Hide() event is called to conceal the current Form's window, then main.ShowDialog() should open the third form.
Afterwards, I call the Close() event to close the previous Form's window entirely.
Here is the code so far:
public partial class Intro_Sequence : Form
{
public static string Username;
public Intro_Sequence(string username)
{
InitializeComponent();
Username = username;
FormBorderStyle = FormBorderStyle.None;
Bounds = Screen.PrimaryScreen.Bounds;
TopMost = true;
intro.uiMode = "none";
intro.URL = AppDomain.CurrentDomain.BaseDirectory + "\\Intro.mp4";
intro.enableContextMenu = false;
DisableMouseClicks();
}
private void DisableMouseClicks()
{
if (this.Filter == null)
{
this.Filter = new MouseClickMessageFilter();
Application.AddMessageFilter(this.Filter);
}
}
private MouseClickMessageFilter Filter;
private const int LButtonDown = 0x201;
private const int LButtonUp = 0x202;
private const int LButtonDoubleClick = 0x203;
public class MouseClickMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref System.Windows.Forms.Message m)
{
switch (m.Msg)
{
case LButtonDown:
case LButtonUp:
case LButtonDoubleClick:
return true;
}
return false;
}
}
private void Intro_Sequence_Load(object sender, EventArgs e)
{
}
private void intro_PlayStateChange(object sender, AxWMPLib._WMPOCXEvents_PlayStateChangeEvent e)
{
if(intro.playState == WMPLib.WMPPlayState.wmppsMediaEnded)
{
Main main = new Main(Username);
this.Hide();
main.ShowDialog();
this.Close();
}
}
}
As you can see I have also added a filter to block clicks during playback, so as not to allow the user to pause it.
However, when I execute this code, it works perfectly fine until it finishes the video and then closes abruptly.
I tried putting breakpoints and everything seems to be fine.
It does call everything I tell it to call, yet the form doesn't even appear.
I have also tried several other alternatives, like not closing the Form at all, calling Show() instead of ShowDialog() and even not Hiding it at all.
It is as if it either freezes there or closes instantly without any sign of the Main form showing.
I also tried calling the Main() form from the Login() and it works perfectly from there.
I really don't know what is going on.
Any help would be appreciated.
How about something like this?
There are three forms. There's a Login form (in this case, it's just an empty form - you close it by clicking on the red X). It is popped up modally from within the Main form (while the main form is hidden).
There's a Splash screen on which your video is to play. I fake out the video by using await Task.Delay(4000); to get a pause. After the 4 second delay, I raise an event (equivalent to your media player event). What I do is show this modally from the main form. I put the event handler in this form; when the event is raised, I close the splash screen modal. The entire (non-designer) code for that form looks like (and, since there are no controls on this form, the designer code is pretty lean):
public partial class SplashScreen : Form
{
public event EventHandler SplashFinished;
public SplashScreen()
{
InitializeComponent();
this.SplashFinished += SplashScreen_SplashFinished;
}
private async void SplashScreen_Load(object sender, EventArgs e)
{
await Task.Delay(4000);
SplashFinished?.Invoke(this, new EventArgs());
}
private void SplashScreen_SplashFinished(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
this.Close();
}
}
Then there's the Main form. It gets fired up in the normal way from Program.cs:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
The only thing that I added to that form (from the out-of-the-box code) is:
private void Form1_Load(object sender, EventArgs e)
{
this.Hide();
var login = new LoginForm();
//should really check this, but for now
login.ShowDialog(this);
var splash = new SplashScreen();
splash.ShowDialog(this);
this.Show();
}
So, when the app starts, the user is shown the login form (the main form is hidden). He does what is needed to do (and the result is checked in the main form's Form1_Load handler.
If everything is cool, a new SplashScreen form is created and shown modally. When it pops up, the video starts (in this case, the video is simply an asynchronous timer). When the video ends, the SplashScreen handles the finished event, and uses it to close itself.
Once control returns to the main form, it displays itself.
I have a method in class where I call loginWindow.ShowDialog(); which brings up a Window, however when you press Close (X in top right) it doesn't Quit the application, rather continues to run whatever is below loginWindow.ShowDialog(); in that method.
How am I able to quit the application entirely if that Window is closed?
I tried to use:
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
e.Cancel = true;
System.Windows.Application.Current.Shutdown();
base.OnClosing(e);
}
Although this didn't shut the application down, which confuses me. When I was using loginWindow.Show(); this wasn't a problem.
I don't know how your application runs, based on your sample code I have two solutions.
Solution 1:- Every window has DialogResult property. Inside the OnClosing event assign DialogResult = true; and call the Shutdown method. The windows who is responsible to call will get the result from return value of ShowDialog() method
For example:-
private void SecondWindow_OnClosing(object sender, CancelEventArgs e)
{
DialogResult = true;
System.Windows.Application.Current.Shutdown();
}
Below event, is from the First screen, calling the Second Window.
private void Button_Click(object sender, RoutedEventArgs e)
{
SecondWindow secondWindow = new SecondWindow();
var dialogResult = secondWindow.ShowDialog();
if (dialogResult.HasValue && dialogResult.Value == false)
{
// any code of yours which must not be executed after the second
// window has closed the process
}
}
Once, the DialogResult is assigned true, the first window will check only if it is false execute the below code or else ignore.
Solution 2:- We will get the Current Application Running Process and Kill the whole process that is your whole application.
private void SecondWindow_OnClosing(object sender, CancelEventArgs e)
{
Process.GetCurrentProcess().Kill();
}
There is a shutdown mode that you can define in the App.Xaml
The default option is OnLastWindowClosed. If it is OnExplicitShutdown than the application wants you to call Application.Shutdown(). What this means is, if you close all windows the application is still running because it is expecting a Application.Shutdown() to be called. This is an explicit shutdown.
Other two options are implicit meaning the Application.Shutdown() method will be called when the last window is closed or when the main window is closed.
Can you check what option you have defined?
I'm trying to do what is described in this post, display a log in window and when user successfully logs in, close it and open the main window of the application.
If the user logs on successfully, then I want to show the main window, if not, I want to exit the application
but the provided answers (at the time of posting this question) do not work for me since my code to show the windows is running from the App.cs.
I know the reason, its because the first window that starts up is automatically set to be the MainWindow of the application and when I call Close() on it, it exits the application. So the second window doesn't have a chance to open.
My question is how to overcome this? Or is this just not possible the way I described?
public partial class App : Application
{
public App(){}
private void Application_Startup(object sender, StartupEventArgs e)
{
LoginScreen f = new LoginScreen(); //becomes automatically set to application MainWindow
var result = f.ShowDialog(); //View contains a call to Close()
if (result == true) //at this point the LoginScreen is closed
{
MainWindow main = new MainWindow();
App.Current.MainWindow = main;
main.Show(); //no chance to show this, application exits
}
}
}
You can change application shutdown mode to OnExplicitShutdown and then call Application.Shutdown(0) whenever you want to. For example:
public App()
{
App.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (MessageBox.Show("Continue?", "", MessageBoxButton.YesNo) == MessageBoxResult.No)
App.Current.Shutdown(0);
}
Here in the constructor I'm changing application shudown mode and calling Shutdown method if I need to.
Caution: When you change ShutdownMode make sure to call Shutdown method otherwise your application will be in memory even after main window closes. I've overrided OnClosed method in my MainWindow to do that:
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
App.Current.Shutdown(0);
}
App.xaml : (In this file set the start window with the login view)
StartupUri="LoginWindow.xaml"
LoginWindow.xaml : (A file with a login window view)
LoginWindow.xaml.cs : (Code Behind for the view. Place here the function assigned to login. )
private void Login_Click(object sender, RoutedEventArgs e)
{
//Access control. If correct, go ahead. Here you must create a condition check
MainWindow main = new MainWindow();
main.Show();
this.Close();
}
On start of my Application Login Form comes up I have simply stored username and password and compared for validating user, if user is valid than MDIparent Form gets opened, Now I want to create logout for this Application. How I can do this?
When I searched I Found That I can do this on FormClosing Event or FormClosed Event but what code should be written in that and for which form, only Dispose(); is enough or something more?
What if I want Login Form to get displayed back?
Showing MDI Form after Successful Login Like this
private void login_Click(object sender, EventArgs e)
{
//if password true then send true
bool value = namePasswordEntry(getHashedUserName, txtUserName.Text, getHashedPassword, txtPassword.Text);
if (value ==true)
{
MessageBox.Show("Thank you for activation!");
this.Hide();
Form2 pfrm = new Form2(txtUserName.Text);
pfrm.ShowDialog();
}
else
{
MessageBox.Show("Invalid LoginName or Password..");
}
}
Try the following codes in the form closing event
Application.Exit(); - Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.
System.Environment.Exit(1); - Terminates this process and gives the underlying operating system the specified exit code.
Application.Restart() - Shuts down the application and starts a new instance immediately.
Source : http://msdn.microsoft.com/
You Should try this on cancel button or your form closing event........................... Application.Exit();
if (value ==true)
{
MessageBox.Show("Thank you for activation!");
this.Hide();
Form2 pfrm = new Form2(txtUserName.Text);
pfrm.ShowDialog();
pfrom.Dispose(); //because user has logged out so the data must be flushed, by "Disposing" it will not be in the RAM anymore, so your hanging problem will be solved
this.Show(); //just add this line here
}
To Logout using Link Label you just need to raise the click event of it. Write this code in the Form2 constructor:
linkLabel1.Click += linkLabel1_Click;
and then create a method:
void linkLabel1_Click(object sender, EventArgs e)
{
this.Close();
}
If anyone still needs this solution:
private void logoutButton_Click(object sender, EventArgs e)
{
this.close();
}
I have this event in a new Form:
private void CrawlLocaly_FormClosed(object sender, FormClosedEventArgs e)
{
}
Im not sure if to use Closed or Closing.
The reason is that i want to check if the user shut down the program for example by just closing the application from the taskbar.
If he did close it from the taskbar mouse right click then close then i want it to close all the program and not only this Form.
How can i do it ?
Application.Exit();
Will shut down your application.
Im not really sure if you can detect if he closed it via rightmouse menu. As far as I know you can only see the reasons provided in the FormClosedEventArgs. FormClosing will provide you with same reasons.
Use this event:
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
if(e.CloseReason == CloseReason.UserClosing)
{
//close forms
Application.Exit();
}
}
There is no way to check whether user closed your form by clicking 'X' or through TaskBar or any other way as the result of CloseReason will always be CloseReason.UserClosing
Well I Stick with such issue also.
In mine app I have 2 forms, #1 main, #2 - for settings - if user close it i want to know save settings or not. Also if settings are null - close app not only form, if user click button save - I want to close (hide) #2 form.
So where is my solution we set tag value to 1 if click button save, so we will know "who" try to close form:
Predefined:
btnSave.Tag = 0;
On save button click event:
btnSave.Tag = 1;
this.Hide();
its will trigger onclose event:
private void frmLogin_FormClosing(object sender, FormClosingEventArgs e)
{
if (btnSave.Tag.ToString() == "0")
{
DialogResult dlg = MessageBox.Show("Do you want to exit without finished setup connection?", "Form", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (dlg == DialogResult.No)
{
e.Cancel = true;
}
else
{
e.Cancel = false;
this.Dispose();
Application.Exit();
}
}
else
{
this.Hide();
}
}