C# 如何在 UserControl 中关闭窗体

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13527474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:54:31  来源:igfitidea点击:

How to close a form in UserControl

c#winformsuser-controlsvisual-c#-express-2010

提问by FJPoort

I created a UserControl with the buttons Save, Closeand Cancel. I want to close the form without saving on the Cancel button, prompt a message to save on the Close button and Save without closing on the Save button. Normally, I would have used this.Close()on the Cancel button, but the UserControl doesn't have such an option. So I guess I have to set a property for that.

我创建了按钮的用户控件SaveCloseCancel。我想关闭表单而不保存在取消按钮上,提示一条消息保存在关闭按钮上,并在不关闭保存按钮的情况下保存。通常,我会this.Close()在取消按钮上使用,但 UserControl 没有这样的选项。所以我想我必须为此设置一个属性。

Scrolling down the "Questions that may already have your answer"section, I came across this question: How to close a ChildWindow from an UserControl button loaded inside it?I used the following C# code:

向下滚动该"Questions that may already have your answer"部分,我遇到了这个问题:如何从加载在其中的 UserControl 按钮关闭 ChildWindow?我使用了以下 C# 代码:

private void btnCancel_Click(object sender, EventArgs e)
{
    ProjectInfo infoScreen = (ProjectInfo)this.Parent;
    infoScreen.Close();
}

This does the job for one screen, but I wonder if I have to apply this code for all the screen I have? I think there should be a more efficient way. So my question is: Do I need to apply this code for every form I have, or is there another (more efficient) way?

这可以在一个屏幕上完成工作,但我想知道是否必须为我拥有的所有屏幕应用此代码?我认为应该有更有效的方法。所以我的问题是:我是否需要为我拥有的每个表单应用此代码,还是有另一种(更有效)的方法?

采纳答案by Tobia Zambon

you can use

您可以使用

((Form)this.TopLevelControl).Close();

回答by FJPoort

I found the simple answer :) I all ready thought of something like that.

我找到了简单的答案 :) 我都准备好想到这样的事情。

To close a WinForm in a ButtonClicked Eventinside a UserControl use the following code:

要在ButtonClicked EventUserControl 内部关闭 WinForm,请使用以下代码:

private void btnCancel_Click(object sender, EventArgs e)
{
    Form someForm = (Form)this.Parent;
    someForm.Close();
}

回答by Lionel D

you can use the FindForm method available for any control:

您可以使用适用于任何控件的 FindForm 方法:

private void btnCancel_Click(object sender, EventArgs e)
{
    Form tmp = this.FindForm();
    tmp.Close();
    tmp.Dispose();
}

Do not forget to Dispose the form to release resources.

不要忘记 Dispose 表单来释放资源。

Hope this helps.

希望这可以帮助。

回答by Michel Oliveira

You also can close one form in any part of the code using a remote thread:

您还可以使用远程线程在代码的任何部分关闭一个表单:

            MyNamespace.MyForm FormThread = (MyNamespace.MyForm)Application.OpenForms["MyForm"];
            FormThread.Close();