2013-03-25 21 views
2

我發現了下面的代碼,它將循環顯示我的項目中所有已關閉的窗體,並打開一個MessageBox並顯示窗體名稱。在我的項目中一次打開所有關閉的表單

但是,我將如何修改它,而不是顯示一個MessageBox;它實際上會逐一打開每個封閉的表單?我寧願使用ShowDialog或類似的東西,因此每個表單只能一次打開1,而不是一次打開。一旦我關閉了一個表單,那麼下一個表單就會打開,等等。

//http://kellyschronicles.wordpress.com/2011/08/06/show-all-forms-in-a-project-with-c/ 
System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetEntryAssembly(); 
Type[] Types = myAssembly.GetTypes(); 
foreach (Type myType in Types) 
{ 
    if (myType.BaseType == null) continue; 

     if (myType.BaseType.FullName == "System.Windows.Forms.Form") 
     { 
      //Application.Run(myType.Name()); //This does not work 
      MessageBox.Show(myType.Name); 
     } 

} 

回答

3

試試這個:

var form = (Form)Activator.CreateInstance(myType); 
form.ShowDialog(); 

你可以用這樣或默認的構造函數中使用它一個帶參數的構造函數,但這有點棘手。
更多請見:Activator.CreateInstance Method

+0

錯誤:錯誤'System.Activator'不包含'Create'的定義 – fraXis 2013-03-25 19:19:35

+0

@fraXis,我知道我剛剛解決了這個問題,對不起。 – 2013-03-25 19:21:33

+0

我將它更改爲Activator.CreateInstance,除了form.ShowDialog()現在獲取此錯誤外沒有錯誤:錯誤'object'不包含'ShowDialog'的定義,也沒有擴展方法'ShowDialog'接受可以找到類型'object'的第一個參數(你是否缺少使用指令或程序集引用?) – fraXis 2013-03-25 19:21:34

0

您需要爲您的Application.Run方法提供新的窗體實例。 嘗試將其轉換爲形式並創建新實例。 事情是這樣的:

public Form TryGetFormByName(string frmname) 
{ 
    var formType = Assembly.GetExecutingAssembly().GetTypes().Where(a => a.BaseType == typeof(Form) && a.Name == frmname).FirstOrDefault(); 
    if (formType == null) // If there is no form with the given frmname 
     return null; 
    return (Form)Activator.CreateInstance(formType); 
} 

從這個帖子Winforms, get form instance by form name

+0

我會怎麼做,與 '類型的myType'?我如何將其轉換爲表單實例? Application.Run((表格)myType.Name());不適合我。 – fraXis 2013-03-25 19:14:37

+0

已更新,以明確說明。請在墨跡中查看更多詳細信息 – evgenyl 2013-03-25 19:20:34

0

試試這個:

if (myType.BaseType.FullName == "System.Windows.Forms.Form") 
    { 
     //Application.Run((Form)myType); 
     Application.Run((Form)Activator.CreateInstance(myType)); 
    } 
+0

無法正常工作:錯誤無法將類型'System.Type'轉換爲'System.Windows.Forms.Form' – fraXis 2013-03-25 19:17:19

1
System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetEntryAssembly(); 
Type[] Types = myAssembly.GetTypes(); 
foreach (Type myType in Types) 
{ 
    if (myType.BaseType == null) continue; 

     if (myType.BaseType.FullName == "System.Windows.Forms.Form") 
     { 
      //Application.Run(myType.Name()); //This does not work 
      //MessageBox.Show(myType.Name); 
      var myForm = (System.Windows.Forms.Form) 
        Activator.CreateInstance(myAssembly.Name, myType.Name); 
      myForm.Show(); 
     } 

} 
相關問題