简体   繁体   English

使用退出按钮关闭一个 winform 程序

[英]Using Exit button to close a winform program

I have an exit button on a winform that I want to use to close the program.我在 winform 上有一个退出按钮,我想用它来关闭程序。 I have added the button name to the FormClosed property found in the events section of the winforms properties.我已将按钮名称添加到在 winforms 属性的 events 部分中找到的 FormClosed 属性。 I thought that's all I had to do but when I click the button it does not close.我以为这就是我所要做的,但是当我单击按钮时它不会关闭。 I looked at the code and while a handler is created, there is no code inside of it.我查看了代码,虽然创建了一个处理程序,但其中没有代码。 I don't know if that is correct or not.我不知道这是否正确。 Here is the code that was created in the Form.cs file:这是在 Form.cs 文件中创建的代码:

private void btnExitProgram_Click(object sender, EventArgs e)
    {

    }

What else do I have to do?我还需要做什么?

this.Close();

以编程方式关闭表单。

Remove the method, I suspect you might also need to remove it from your Form.Designer .删除该方法,我怀疑您可能还需要从Form.Designer删除它。

Otherwise: Application.Exit();否则: Application.Exit();

Should work.应该管用。

That's why the designer is bad for you.这就是设计师对你不利的原因。 :) :)

The FormClosed Event is an Event that fires when the form closes. FormClosed 事件是在窗体关闭时触发的事件。 It is not used to actually close the form.它不用于实际关闭表单。 You'll need to remove anything you've added there.您需要删除在那里添加的任何内容。

All you should have to do is add the following line to your button's event handler:您所要做的就是将以下行添加到按钮的事件处理程序中:

this.Close();

We can close every window using Application.Exit();我们可以使用Application.Exit();关闭每个窗口Application.Exit(); Using this method we can close hidden windows also.使用这种方法我们也可以关闭隐藏的窗口。

private void btnExitProgram_Click(object sender, EventArgs e) { Application.Exit(); }

使用以下代码

System.Windows.Forms.Application.Exit( ) 

把这个小代码放在按钮的事件中:

this.Close();

Try this:尝试这个:

private void btnExitProgram_Click(object sender, EventArgs e) {
    this.Close();
}

In Visual Studio 2015, added this to a menu for File -> Exit and in that handler put:在 Visual Studio 2015 中,将此添加到 File -> Exit 的菜单中,并在该处理程序中放置:

this.Close();

but the IDE said 'this' was not necessary.但是 IDE 说“这”不是必需的。 Used the IDE suggestion with just Close();仅通过Close();使用 IDE 建议Close(); and it worked.它奏效了。

If you only want to Close the form than you can use this.Close();如果您只想关闭表单,则可以使用 this.Close(); else if you want the whole application to be closed use Application.Exit();否则,如果您希望关闭整个应用程序,请使用 Application.Exit();

You can also do like this:你也可以这样做:

private void button2_Click(object sender, EventArgs e)
{
    System.Windows.Forms.Application.ExitThread();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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