private DialogResult AskFileName()
{
using (Form myForm = new SaveFileDialog();
{
// Before showing the dialog box, set some properties:
myForm.Title = "Save file";
myForm.FileName = this.DefaultFileName;
myForm.ValidateNames = true;
...
// show the file save dialog, and wait until operator closes the dialog box
DialogResult dlgResult = myForm.ShowDialog(this);
// if here, you know the operator closed the dialog box;
return dlgResult;
}
}
private void SaveFile()
{
DialogResult dlgResult = this.AskFileName();
switch (dglResult)
{
case DialogResult.Ok:
// File is saved:
this.HandleFileSaved();
break;
case DialogResult.Cancel();
// operator pressed cancel
this.ReportFileNotSaved();
break;
...
}
}
class MyModelessDialogBox : Form {...}
class MyForm : Form
{
private MyModelessDialogBox {get; set;} = null;
private void ShowMyModelessDialogBox()
{
if (MyModelessDialogBox != null)
{
// Dialog box already shown, TODO: report to operator?
...
return;
}
else
{
// Dialog box not shown yet; create it and show it
this.MyModelessDialogBox = new MyModelessDialogBox();
// if needed, before showing set some properties
// make sure you get notified if the dialog box is closed
this.MyModelessDialogBox.FormClosed += new FormClosedEventHandler(this.MyModelessDialogBoxClosed);
// show the dialog box:
this.MyModelessDialogBox.Show(this); // I am the owner / parent window
}
// when the modeless dialog box is closed, you get notified:
void MyModelessDialogBoxClosed(object sender, FormClosedEventArgs e)
{
// if needed, inspect e.CloseReason
// if needed, handle the DialogResult
// finally: not my form anymore. The form should disposes itself:
this.MyModelessDialogBox = null;
}
}
}} 关闭表单之前,应检查对话框是否显示,然后关闭:
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
if (this.MyModelessDialogBox != null)
{
// the modeless dialog box is being shown. Order it to close itself:
this.MyModelessDialogBox.Close();
// this will lead to MyModelessDialogBoxClosed
}
}
bool RequestToClose()
{
bool allowedToClose = this.AskOperatorIfCloseAllowed();
if (allowedToClose)
{
// close this dialog box.
this.Close();
// the owner of the dialog box will be notified via MyModelessDialogBoxClosed
}
return allowedToClose;
}
2条答案
按热度按时间lkaoscv71#
实际上,在互联网上有大量的例子,首先你应该创建你的两个表单,然后在form1的按钮事件下创建一个form2的示例,并调用它的Show()方法。
下面是你应该遵循的过程的一步一步的解释。我建议你也看一些基本的c#编程教程。Click Here
e0bqpujr2#
如果您使用windows已有一段时间,就会注意到有两种类型的对话框(窗体):Modal and Modeless Dialog Boxes
如何显示模式对话框
为此,可以使用Form.ShowDialog
在您的表单中:
窗体是一次性的,因此应该使用using语句。创建窗体后,您有时间设置属性。窗体使用
ShowDialog
显示。显示此对话框时,窗体无法获得焦点。操作符关闭对话框后,窗体再次获得焦点。ShowDialog的返回值指示结果。如果您想在操作员选择菜单项"文件保存"或按下按钮"保存"后保存文件,请执行以下操作:
如何显示无模式对话框
使用Form.Show显示一个非模态对话框。调用这个函数后,你的对话框可以获得焦点。因此你必须记住窗体正在显示。
}}
关闭表单之前,应检查对话框是否显示,然后关闭:
有时候你有一个对话框拒绝关闭,比如因为对话框警告操作员,他点击了取消,在这种情况下,你不应该直接关闭对话框,而应该添加一个方法来友好地询问对话框。
在对话框中: