How to fix 'Cannot access a disposed object'? - c#

So I'm trying to make a simple command prompt using ConsoleControl latest version. My code is very simple :
public CommandPrompt()
{
InitializeComponent();
}
private void CommandPrompt_Load(object sender, EventArgs e)
{
consoleControl1.StartProcess("cmd", string.Empty);
}
private void CommandPrompt_FormClosing(object sender, FormClosingEventArgs e)
{
consoleControl1.StopProcess();
}
The problem is on FormClosing event. Whenever I close the window and re-open it just after (sometimes it triggers the exception just when closing), it produces a "Cannot access a disposed object" exception.
I can't seem to fix it. The problem is the StopProcess() method as I saw myself. So I've decided to manually terminate the cmd process using Process.Kill(), but still the same exception. It seems like, for some reason, terminating the cmd process when the form is closing throws this exception.
The only way that I found to terminate the process via the program is by using the command taskkill or tskill. But I want it to automatically terminate after the form closes.
Any help is greatly appreciated!

I'm answering my own question because I found the solution.
I just had to use an instance of the form and hide it instead of closing it.
Here's my code now :
public CommandPrompt()
{
InitializeComponent();
}
private void CommandPrompt_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
Hide();
}
private void CommandPrompt_Shown(object sender, EventArgs e)
{
consoleControl1.StopProcess();
consoleControl1.StartProcess("cmd", string.Empty);
}
And when showing the form :
private CommandPrompt cmd = new CommandPrompt();
private void Button19_Click(object sender, EventArgs e)
{
cmd.Show();
}
Hope it can help other people too!

Related

Close application after closing dialog window

Sorry for (maybe) easy question, but how can I shut down application, when I close dialog window ( which I called before running MainWindow) ?
As I mentioned above, before running MainWindow in my application I call a Dialog window. In App.xml I added this:
Startup="Application_Startup"
Then in App.xml.cs I wrote this:
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
StartWindow startWindow = new StartWindow();
startWindow.ShowDialog();
}
}
In my StartWindow there are only two exits - connect button, that worked fine, and classic closing button on title bar. I would like this button to shut down my application.
In my class StartWindow I wrote this:
private void Window_Closed(object sender, EventArgs e)
{
DialogResult = false;
}
But it still runs my MainWindow after closing my StartWindow. I even tried
private void Window_Closed(object sender, EventArgs e)
{
DialogResult = false;
Application.Current.Shutdown();
}
But still. Even if in above code I changed rows.
What I am doing wrong? I suspect, that is very easy to program what I want, but I don't know how. Yet. Can you help me, please?
ShowDialog() has a return value.
bool? dialogResult = startWindow.ShowDialog();
if (dialogResult == false)
{
...
}
You have to set DialogResult in your StartWindow before closing it, but you have already done that.

Best Way to Close a Win Form

I need to close a form on a button click event.Here in my example I am hiding the form.Think this is not a good way.When I do only Close() the form is disposed forever and need to rerun the programme to retrieve it.
private void buttonClose_Click(object sender, EventArgs e)
{
this.Close(); //closing frmCalender
}
private void frmCalender_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
this.Hide();
e.Cancel = true;
}
}
Give me the best way to close a C# Windows Form.
If you want to close a form, call .Close().
When I do only Close() the form is disposed forever and need to rerun the programme to retrieve it.
When you close the form, I assume you have no references to it. If so, you can create a new copy of your form via the constructor (var form = new MyForm();).
Otherwise, after closing the form, I believe you should be able to call .Show() on it again, as long as something still has a reference to your form.
I think, the best approach would be:
private void buttonClose_Click(object sender, EventArgs e)
{
this.Hide();
}

An object reference is required for the non-static field, method, or property 'System.Diagnostics.Process.CloseMainWindow()'

I Get this error Error 1 An object reference is required for the non-static field, method, or property 'System.Diagnostics.Process.CloseMainWindow()'
I get that error on Process.CloseMainWindow();
Could you tell me where my mistake is? I'm trying to make it that when you click x on the c# win form app it to kill the process.
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
Process.CloseMainWindow();
}
The Process class is used to handle external processes.
You need to get the Process you want to close.
Process process = Process.GetProcessesByName("myProcess").FirstOrDefault();
if (process != null)
{
process.CloseMainWindow();
}
But if you are closing a child form and you want it to exit your application use
Environment.Exit(0);// or whatever exit code you need
or as #Nico Schertler metioned
Application.Exit();
But if this is your main form and you click X is should close without any other code.
I used Application.Exit(); - just as Nico Schertler said. (Thanks btw)
Here's the working code:
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
You must change your method to static
private static void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
Process.CloseMainWindow();
}

How do I close an open file?

This button opens a text file which has error log information:
private void btnViewErrorLogFile_Click(object sender, EventArgs e)
{
Process.Start(AppVars.ErrorLogFilePath);
}
When the user goes to do any processing in the application, I want to check whether the file is open or not, if it is open, then I want to close it. How would I go about doing this?
This example is almost identical to what you're trying to do:
Process.Close Method
Process myProcess;
private void btnViewErrorLogFile_Click(object sender, EventArgs e)
{
myProcess.Start(AppVars.ErrorLogFilePath);
}
private void doSomething()
{
if (!myProcess.HasExited)
{
myProcess.CloseMainWindow();
myProcess.Close();
}
// Do whatever you need with the file
}
Shows how to check if it's running and how to close it.

logout the main form and show the login form

i know this problem may sound stupid, but sad case, i've been searched online to get solution but still cannot get it correct. My problem now is = Logout button so to exit the main form, then show up the login form again.
The code below will NOT show the login form after i click the logout button, it straight away exit the whole application.
void logoutbtn_Click(object sender, EventArgs e)
{
CloseSockets();
this.Close();
serverlogin login = new serverlogin();
login.Show();
}
So, i try to replace this.Hide() instead of this.Close();. But, something even dumb happen. Yes, the login page show after i click the logout button, but when i click the Cancel button at my login form, it didnt exit the whole application where it suppose to exit the whole application. i guess is because the main form is just hiding and not yet close??? Plus, when i try to login again, the login button is also, NOT functioning, cannot login to main page.
i apologize upon my explanation and please tell me if it is very unclear.
Please kindly help me. Thank you so much.
You need to define 2 event in your form which will be fired on butttons click and handle it in the main form:
MainForm.cs
void logoutbtn_Click(object sender, EventArgs e)
{
CloseSockets();
this.Hide();
serverlogin login = new serverlogin();
login.Login += new EventHandler(serverlogin_Login);
login.Cancel += new EventHandler(serverlogin_Cancel);
login.Show();
}
private void serverlogin_Login(object sender, EventArgs args)
{
this.Show();
// do login
}
private void serverlogin_Cancel(object sender, EventArgs args)
{
Application.Exit();
// do exit
}
LoginForm.cs
public event EventHandler Login;
public event EventHandler Cancel;
private void OnLogin()
{
if (Login != null)
Login(this, EventArgs.Empty);
}
private void OnCancel()
{
if (Login != null)
Login(this, EventArgs.Empty);
}
private void btnLogin_Click(object sender, EventArgs e)
{
this.OnLogin();
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.OnCancel();
}
You might just want to start a new instance of your application, then exit the old one, when "logout" is selected. This cleans up any resources still in use, and makes it much more difficult to leak data from one user session to the next.
The disadvantage, of course, is that it will be slower, but there's ngen.exe to reduce the cost of restarting the app.
I reviewed the first answer, and I found out that there is something wrong. In the code, he closes the form after creating the new thread. I tested it, but it always closed my form. So I switched the this.Close(); with t.Start(); and it worked. Below you have the explanation of the code.
You create a new thread then you close the form you are in (for exemple the menu), and finally you start your new thread. You create a new method where you run your new form. I commented it line by line.
private void btnLogout_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(OpenLoginForm)); //you create a new thread
this.Close(); //you close your current form (for example a menu)
t.Start(); //you start the thread
}
public static void OpenLoginForm()
{
Application.Run(new LoginForm()); //run your new form
}
private void btnLogout_Click(object sender, EventArgs e)
{
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(OpenLoginForm));
t.Start();
this.Close();
}
public static void OpenLoginForm()
{
Application.Run(new LoginForm());
}

Categories

Resources