简体   繁体   中英

C# Ending process on Form2 close

I'm trying to work with multiple forms, what I want is change the way the form is depending on the selected index of a combobox, the only way I could think of is hide form1 and show form2, but the problem is when you close form2, the process does not end...I tried the code below

private void Form2_FormClosing(object sender, FormClosedEventArgs e)
    {
        foreach (var process in Process.GetProcessesByName("Process Name.exe"))
        {
            process.Kill();
        }
    }

if there isn't, is there a way the form can change on combobox selected index?

Try Application.Exit();

It exits your entire application and closes all your forms and threads.

Simply pass an instance of Form1 to the constructor of Form2, keep a reference to it in a form1 member

public class Form2 : Form{
    private Form _form1;

    public Form2(Form form1):this()
    {
        _form1 = form1;
        InitializeComponent();
    }
}

later you can simply use that reference :

_form1.Close();

This is a cleaner way to do it. Other mechanisms are also ok, like implementing an eventhandler on form1 for an event in form2.

based on your pastebin code change this:

Form2 HeadquarterForm = new Form2(this);

you also only need the closed eventhandler and call close on the _form1 only once. So you don't really need the closing event handler.

The process is still running because form1 is still alive but hidden.

Try using Environmental.exit() to kill the process

Looking at your code in pastebin. Problem is, you're not passing Form1 in constructor of your Form2 when creating it. Change the part of your switch-case (4) to:

Form2 HeadquarterForm = new Form2(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM