Hide or Dispose Form - c#

I have a MainForm, from the MainForm i call the ConfirmationForm,
using (var f = new ConfirmationForm())
f.ShowDialog();
Then in the ConfirmationForm, i want to show the another UsersListForm
if (ConfirmSuccess)
{
this.Hide; //or this.Close
using (var f = new UsersListForm())
f.ShowDialog();
}
Now, when the ConfirmSuccess is equal to true the MainForm will Hide or Close too. How to prevent that the MainForm will not to Hide or Close? any idea? Thanks in advance.
UPDATE: My problem is solve. I call first the UsersListForm and from the load event of UsersListForm I call the ConfirmationForm then I use DialogResult == System.Windows.Forms.DialogResult.OK and everythings is fine now :)

If your intention is to request user confirmation before opening the MainForm, the best way to do this would include you call and confirmation form after creating it and call MainForm.
If your intention is to seek confirmation at the beginning of the application, place the call ConfirmationForm within the Program class before the Application.Run (new MainForm ());
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ConfirmationForm confForm = new ConfirmationForm();
confForm.ShowDialog();
Application.Run(new MainForm());
}
}
But if the intention is to request verification within the application in a separate call point, you should call the ConfirmationForm with ShowDialog and after that call the desired form.
But if your intention really is to verify the request with the open form, and hiding it, you can use the DialogResult property of ConfirmationForm to return the success or failure of the validation by comparing (ConfirmationForm.ShowDialog () == DialogResult.OK). See this example

Related

Parent form and Child form in Loop C#

I am trying to create a login for my tool and have sorted that but when they press login(Child form) the program loops and asks the user to login again. I notice when I press the 'Exit' button it then loads the Parent form fine but I dont want that. I want my users to press login and then go right to the Parent form.
To open the child form before the parent form inside of Form1_Load I have this:
Login Log = new Login();
Log.ShowDialog();
Inside the 'Login' button on the child form I have this:
this.Hide();
Form1 Main = new Form1();
Main.Show();
The best way to handle this would be to handle the login BEFORE your form starts (e.g. in the Program.cs but after the application initialization). Insert a variable into your login form (E.g. a bool that shows if they have passed your authorization test) and check after the form has closed to see what the status of authorization is. If the flag is set to false then you can do a return or Application.Exit() and the user will never see the main form.
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SomeLoginForm Login = new SomeLoginForm();
Login.ShowDialog();
if (!Login.HasPassedAuthorization)
{
MessageBox.Show("Sorry you failed to pass the test! I'm kicking you out now!");
Application.Exit(); // or do a "return;"
}
Application.Run(new Form1());
}
}
static class SomeLoginForm()
{
internal bool HasPassedAuthorization;
}

C# app stays in task manager after closing [duplicate]

why The process still on Windows Task list manager after close programme ?
i use login Form.cs
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Login());
}
after the user succesuly login, i redirect to another Masterpage
this.Hide();
Main_Usr oMainUsr = new Main_Usr();
oMainUsr.Visible = true;
my pseudo master page like this:
public Main_Usr()
{
InitializeComponent();
this.IsMdiContainer = true;
}
when i close the masterpage, The process still on Windows Task list manager.
But when i close the login page, it kill the process on Windows Task list manager.
is that mean because i just hide le login page ?
must i close all window to realy quit/kill the process ?
Thanks you in advance,
Stev
In winforms process will be killed, when main application form is closed. Main application form is one specified in Application.Run call. In your case it is Login form:
Application.Run(new Login());
To close form you should call Close method. When you call Hide or set Visibility to false, form stays in memory. It just becomes hidden from user.
So, to achieve desired functionality you should change main application form to Main_Usr:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Main_Usr()); // change main form
}
Then subscribe to Load event of Main_User form. And in the event handler do following:
private void Main_User_Load(object sender, EventArgs e)
{
using (var loginForm = new Login())
{
Hide(); // hide main form
if (loginForm.ShowDialog() != System.Windows.Forms.DialogResult.OK)
{
Close(); // close main form and kill process
return;
}
Show(); // show main form if user logged in successfully
}
}
UPDATE: You can do this all in Main method, like this way
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
using(var loginForm = new Login())
if (loginForm.ShowDialog() != System.Windows.Forms.DialogResult.OK)
return;
Application.Run(new Main_Usr()); // change main form
}
but usually I don't hide main form and show it below login form. So, in this case you should use Load event handler. It's up to you.
BTW there is no masterpages and pages in winforms. This all is for ASP.NET. Here you have forms :)
Also consider naming like LoginForm, MainForm etc.
This is because the application message loop is associated with your Login form (Application.Run(new Login()) does this), so you need to close the form which started the application to end the process.
Alternatively, you could just call LoginForm.Show(), before Application.Run, store credentials somewhere and then call Application.Run(new Main_Usr)
Because Login is the last form of the application to close, you load Main_User only after that - even if Login is hidden it's still actually there. Windows Forms applications are by default configured to exit when the last form closes.
this.Hide()
doesn`t kill the window.
So it remains hidden and process remains in memory.
this.Close() closes the window and removes its object from memory.
It is better to do something like this:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var l = new Login();
l.ShowDialog();
if(l.Passed)
Application.Run(new Login());
}
And implement Passed property inside login window.
By the way, do you have any multithreading inside?
It is another source of errors of this type.
i found it, i just use the dizlog.
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Login oLogin = new Login();
oLogin.ShowDialog();
Application.Run(new Main_Usr());
}
i follow code the #lazyberezovsky and add this on my Login.cs
private void simpleButton_Valider_Click(object sender, EventArgs e)
{
.....
DialogResult = DialogResult.OK;
return;
.....
}

Close The Entry Form

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form_Login());
After Login I Wanna Make The New Form Which Shown up After Login Is The Main Form And Close Current Form
I Tried
This.Hide();
and It Just Hide The Form But It 's Still Running On Task Manager
And I Tried
This.Close();
It Close The Whole Application Because The Form_Login Is The Main Form
Return a DialogResult upon closing your Form1. Use that value in Main() to determine if you should open Form2 or not. Something like this.
In Form1, perhaps in a button click handler:
this.DialogResult = DialogResult.OK;
this.Close();
In Program.cs:
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form1 = new Form1();
Application.Run(form1);
if (form1.DialogResult == DialogResult.OK) {
Application.Run(new Form2());
}
If your Form1 closes without setting its DialogResult to DialogResult.OK, your application will exit. If your Form1 closes and its DialogResult is set to DialogResult.OK then Form2 will open.
Edit: Using this technique for simple logons
Here's one approach.
Create an enum which describes the result of your logon screen:
public enum LogonStatus { NoLogon, UserA, UserB };
On your logon screen create a property to store the logon result:
public LoggedOnUser User { get; private set; }
In the logon form assign a value to the logon operation and close the form:
LogonResult = LogonStatus.UserA; // UserA logged in, for example.
this.Close();
In Main run the Logon form, examine the form's LogonResult proeprty and process the result:
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var loginForm = new Form_Login();
Application.Run(loginForm);
if (loginForm.LogonResult == LogonStatus.NoLogon) {
// Do something because there was no logon, or do nothing here and let your app exit.
} else {
// Launch your application form, passing in the logged on user.
Application.Run(new AppForm(loginForm.LogonResult));
}
}
This example shows passing a LogonStatus to your AppForm's constructor to allow you to tailor it the user logged on.
With the above said though, you should know this isn't really the best way to do this. A more flexible and robust solution would involve taking advantage of Windows directory services.

I have a system task tray application - Can I close the main form instead of just hiding it?

I have an application that has a main form and a system task tray icon. In the designer of the main form, I dragged the TrayIcon control on the form, so it is a child of the main form.
At this point, when the user presses the close button on the main form, it actually just hides it so that the application wont terminate, unless the user right clicks the TrayIcon and clicks exit. But, the main form has a lot of controls and resources, and when the main form is hidden, it still uses memory for those resources. My goal is to actually dispose of form so it doesn't take up that memory while it is not being used.
Unless I am mistaken, and when the main form is hidden it doesn't take up that memory anymore, but I don't think that is the case.
I'm no expert on memory, I may even be completely mistaken on how memory management works, and thus this question is invalid.
Anyways, if I am correct in that when the main form is only hidden it still takes up memory that can be freed by fully closing the form, is there a way for me to actually close the main form without the application terminating? If so, I would need to create the TrayIcon with code in the Program class instead of in the class of the main form, correct?
No, that's certainly not necessary. It is encouraged by the convenience of the designer but you can easily create an application that only creates a window on demand. You'll have to write code instead. It doesn't take a heckofalot, there's a sample app with basic functionality. Edit the Program.cs file and make it look similar to this (icon required, I called it "SampleIcon"):
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var cms = new ContextMenuStrip();
cms.Items.Add("Show", null, ShowForm);
cms.Items.Add("Exit", null, ExitProgram);
var ni = new NotifyIcon();
ni.Icon = Properties.Resources.SampleIcon;
ni.ContextMenuStrip = cms;
ni.Visible = true;
Application.Run();
ni.Dispose();
}
private static void ShowForm(object sender, EventArgs e) {
// Ensure the window acts like a singleton
if (MainWindow == null) {
MainWindow = new Form1();
MainWindow.FormClosed += delegate { MainWindow = null; };
MainWindow.Show();
}
else {
MainWindow.WindowState = FormWindowState.Normal;
MainWindow.BringToFront();
}
}
private static void ExitProgram(object sender, EventArgs e) {
Application.ExitThread();
}
private static Form MainWindow;
}

c# Windows form application forms problem

I have a c# windows form app which contains several forms.
Generally, for example, in form1, I create a instance of form2 and then
form1.hide();
form2.show();
But sometimes I want the previous form to show and dispose current form. How can I call the previous form?
Thanks in advance.
To answer your question, you need to maintain references in your views to each other. While this might work it's messy and error prone. It sounds like all your control logic is probably contained within your form class code and I would suggest moving away from that and separate your concerns.
Solving your form management issues becomes very simple if you create a controller class that, at a minimum, manages the creation and disposal of your forms in whatever way you see fit.
So your code sample would actually be launched from a controller class as something like:
public class FormsController
{
private Form form1 = new Form();
private Form form2 = new Form();
public void SwitchForms()
{
form1.hide();
form2.show();
}
}
For further edification checkout the MVC architectural pattern for cleanly working with data, biz logic and UI.
You might consider extending Form to include some properties/fields that allow you to access other forms. the Form class can be inherited from just like most other .Net classes.
You may also consider doing some of that management in the Program.cs file that is part of you project, if neither form is really supposed to be a child of the other.
If you inherit a new class for your form1 from Form and add a method like closeSecondForm you can have it close and dispose the second form.
There are probably a bunch of different ways to solve the issue. These are just a few.
If you set the new form's Owner to a reference to the current form, you can reference that Owner from the new form. You could also subscribe to the new form's Closed() event from the old form, with code to dispose it (though the form can dispose itself by overriding OnClosed, if it doesn't happen there anyway).
This logic should be handled in Program.cs. The Main() method initializes Form1. You want to take control there instead of passing control to the form.
Example:
static class Program
{
internal static Form1 MyForm1;
internal static Form2 MyForm2;
///
/// The main entry point for the application.
///
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
// Initialize Form1
MyForm1 = new Form1();
MyForm1.FormClosing += new FormClosingEventHandler(MyForm1_FormClosing);
// You may want to initialize Form2 on-demand instead of up front like here.
MyForm2 = new Form1();
MyForm2.FormClosing += new FormClosingEventHandler(MyForm2_FormClosing);
// Show Form1 first
MyForm1.Show();
// Now we need to occupy the thread so it won't exit the app. This is normally the job of Application.Run.
// An alternative to this is to have a third form you pass on control to.
while (true)
{
Application.DoEvents();
System.Threading.Thread.Sleep(10);
}
}
static void MyForm1_FormClosing(object sender, FormClosingEventArgs e)
{
// Do something, for example show Form2
MyForm2.Show();
// EXAMPLE: We only want to hide it?
e.Cancel = true;
MyForm1.Visible = false;
}
static void MyForm2_FormClosing(object sender, FormClosingEventArgs e)
{
// Do something, for example show Form1
MyForm1.Show();
// EXAMPLE: We only want to hide it?
e.Cancel = true;
MyForm2.Visible = false;
}
}
Since Program is static you can access MyForm1 and MyForm2 anywhere in that project by:
Program.MyForm1.Show();
Program.MyForm2.Hide();
If you plan to have many forms/complex logic I suggest moving this to a separate class. Also consider using a single form and rotate user controls inside it instead.
Form2 myform = new Form2();
myform.show();
this.hide();
You could do this in form1:
...
var form2 = new form2();
form2.Closing += (form2_Closing);
this.hide();
form2.show();
...
private void form2_Closing(object sender, System.EventArgs e)
{
this.show();
}

Categories