【问题标题】:C# Winform load methodC# Winform 加载方法
【发布时间】:2014-03-18 09:51:44
【问题描述】:

我正在编写 WinForm 应用程序,其中每个新表单都是主表单的子表单。每次我调用 menustripitem click 我都会使用这样的代码:

bool opened = false;
foreach (Form forma in Application.OpenForms)
{
    if (forma is frm_formname)
    {
        opened = true;
        break;
    }
}

if (!opened)
{
    frm_formname frm = new frm_formname();
    frm.MdiParent = this;
    frm.Show();
}
else
{
    MessageBox.Show("Form already exist");
}

如何更改代码以从此代码创建一个方法,在该方法中我将传递 formname 和 mainformname 作为参数,并在单击事件时调用此方法发送这 2 个参数而不是整个代码?

【问题讨论】:

  • 将代码移动到单独的函数的约束是什么。看起来直截了当的工作。

标签: c# winforms


【解决方案1】:

你不能使用字符串,你应该传递你正在寻找的表单的类型作为参数。 像这样的东西应该可以工作(未经测试!)。

public void FindOrCreateForm(Type formType)
{
bool opened = false;
foreach (Form forma in Application.OpenForms)
{
    if (forma.GetType() == formType)
    {
        opened = true;
        break;
    }
}
if (!opened)
{
    Form frm = (Form) Activator.CreateInstance(formType);
    frm.MdiParent = this;
    frm.Show();
}
else
{
    MessageBox.Show("Form already exist");
}
}

【讨论】:

  • 我试过这个 - 作为 formType 我发送表单名称,我收到错误:参数 1:无法从 'Modules.frm_TestForm' 转换为 'System.Type' 并且 'Modules.frm_TestForm' 是一个 'type ' 但用作'变量'
  • 尝试传递 Modules.frm_TestForm.GetType() 或 typeof(Modules.frm_TestForm) 作为参数
  • 它可以工作,但还有一个问题 - mdi child - frm.MdiParent = 这显示错误 - 无法将类型“Mod.GetForm”隐式转换为“System.Windows.Forms.Form”
  • 您需要像这样进行显式转换:frm.MdiParent = (Form)this;
猜你喜欢
  • 2012-09-09
  • 2013-03-27
  • 1970-01-01
  • 1970-01-01
  • 2012-03-14
  • 2016-10-31
  • 2010-12-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多