Parent form and Child form in Loop C# - 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;
}

Related

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;
}

Hide or Dispose Form

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

Need to define control flow and functionalities

I have a project with requirements as below,
Login form opens up and asks for user name and password.
Login Successful - Login form closes and another main form opens and all the functionalities will be added here.
In the main form there is a Call button when clicked on it, it will pop a dial pad.
When the number is entered on the dial pad and clicked "ok", control comes back to the same main form.
When logout is clicked, It wil take me to the login screen again.
For this can anybody explain me the following points:
How do I tranfer the control from one form to another?
I have to make sure when user clicks on the close 'x' , I have to log out and close the windows?
Neeed some rough class information.
Thanks in advance.
This is what i used earlier to carry data from one form to other
public partial class DialPad : Form
{
public MainGUI guiObject;
public DialPad(MainGUI mG)
{
InitializeComponent();
guiObject = mG;
}
By the sounds of it your dialler form should be a dialog..
class MyDiallerDialog : Form
{
public String DialledNumber
{
get { return this.txtNumber.Text; } // Or however the form stores its number...
}
}
class MyMainForm : Form
{
void btnCall_Click(object sender, EventArgs e)
{
using (var dialog = new MyDiallerDialog())
{
if (dialog.ShowDialog() == DialogResult.OK)
{
String number = dialog.DialledNumber;
// do something interesting with the number...
}
}
}
}
For your point no. 2
I have to make sure when user clicks
on the close 'x' , I have to log out
and close the windows?
In the event FormClosing of the form, take a look at e.ClosingReason.
So if user closes using Close Button (X), then ClosingReason would be UserClosing. So check that and then write appropriate code therein.
How do I tranfer the control from one
form to another?
For e.g
If you want to get the number in main form from Dialpad form.
1st in the contructor of main form
public static MainForm instance = null;
public string numberInMainForm = null;
public MainForm()
{
instance = this;
}
now in your dialpad form, when user enters the number, you can pass the number (or any other variable.) to main form from the dialpad form directly.
In dialpad form just write:
MainForm.instance.numberInMainForm = number;
thats it. You are done !!
let us assume you 1st form is loginform,
Suppose User press OK on the login form, so on
OK_click()
event call another form.
suppose your name of the another form is MainForm.cs then you can call using...
MainForm mf = new Mainform()
Suppose you want to close the login form when user press OK of your logIn form you can keep the order in following way..
private void OK_Click(object sender, EventArgs e)
{
. . .
// your validations
//return bool (true or false ) to confirm you have complted validations
MainForm mf = new Mainform();
mf.show(); // or you can use mf.ShowDialog();
. . .
. . .
this.close();
}
When you will close the MainForm,its control will come directly to the next line after mf.show();
To close any form use
this.close() command.
I hope this will help you ands you can start working on your project now.
EDIT:
Add a new class file named commondata.cs and in that use static variables like
public static string myString = "";
You can keep all the static functions and variables in the common file like commonData.cs so that you can modify its value from anywhere and can be used from anywhere.
Before closing your current form store the information in the static myString so even if u close the current form related information will be stored in myString & you can access it in any form using commonData.myString command.
string temp = commonData.myString;
Regards,
Sangram Nandkhile.

Categories