2013-10-07 37 views
0

我有一個項目是「主」,啓動項目的多項目解決方案。
從這個項目我開始在所有啓動項目中引用的其他項目中的窗體。在其他項目中顯示單實例

問題是,我可以啓動這些形式是這樣的實例:

Dim ka As New otherproject.frm_thatform 
    With ka 
     .BringToFront() 
     .Show(Me) 
    End With 

打開新的「thatform」每一次,但我想開始「thatform」像單一實例每次和「這種形式「出現在前面。

如何做到這一點?

我嘗試這樣的:

Dim ka As otherproject.frm_thatform 
With ka 
    .BringToFront() 
    .Show(Me) 
End With 

...但不工作(未將對象引用設置到對象的實例)。

回答

1

訣竅是不昏暗的形式並將其用作共享對象。

Otherproject.frm_thatform.Show() 
Otherproject.frm_thatform.BringToFront() 

只要你不關閉這個窗口,你可以像調暗對象一樣調用它。相反,KA的

你只需要輸入Otherproject.frm_thatform

只要你關閉它會在它失去一切的窗口。

編輯:顯然這隻適用於項目內的形式。我的壞:(

你需要做的,而不是什麼是保持形態的名單你的主要項目中。

確保你給的形式的名稱,當您單擊該按鈕以打開的形式簡單循環在列表中找到設置名稱

事情是這樣的:

Private FormList As New List(Of Form) 
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click 
    Dim theForm As Form = Nothing 
    For Each f As Form In FormList 
     If f.Name = "Selected form name" Then 
      theForm = f 
     End If 
    Next 
    If theForm Is Nothing Then 
     theForm = New Otherproject.frm_thatform() 
     theForm.Name = "Selected form name" 
     FormList.Add(theForm) 
    End If 
End Sub 
+0

WozzeC嗨,東西仍然缺少C#代碼。我收到錯誤「引用非共享成員需要對象引用」。我應該使Otherproject.frm_thatform SHARED以某種方式? –

+0

據我所知,公共類frm_thatForm應該足夠了。但我會用跨項目表格進行測試。這是一種可能性,它只適用於內部形式。 – WozzeC

+0

嗯似乎沒有工作跨項目。只有在內部,我會做一些其他的測試。 – WozzeC

1

在你的原代碼,移動窗體聲明出來級(形式)級別:

Private ka As otherproject.frm_thatform = Nothing 

然後檢查,看它是否是沒有或已被釋放,並在必要時重新創建:

If (ka Is Nothing) OrElse ka.IsDisposed Then 
    ka = New otherproject.frm_thatform 
    ka.Show(Me) 
End If 
If ka.WindowState = FormWindowState.Minimized Then 
    ka.WindowState = FormWindowState.Normal 
End If 
ka.BringToFront() 
+0

這是一個有趣的方法。爲了得到它的工作,我應該調用不帶Me關鍵字的Show方法。 –

+0

這只是告訴形式誰是「所有者」,將它們連接在一起。最小化所有者也最小化「孩子」。它使他們像一個單位一起工作。 –

+0

奇怪的是,第二次打開我得到錯誤消息「已經可見的窗體不能顯示爲模態對話框。在調用Show之前將窗體的可見屬性設置爲false。如果跟我一起打電話。此外,「如果沒有(ka)」不適合我,但「如果沒有什麼」的確奏效。 VB2008,NET 2.0,win7/64。 –

1

幾個選項 -

  1. 創建靜態/共享形式變量
  2. 
    Shared form As SingletonformEx.Form1 
    If form IsNot Nothing Then 
        form.BringToFront() 
    Else 
        form = New SingletonformEx.Form1() 
        form.Show() 
    End If 
    
  3. 擴展表單類並在其上實現單例模式。
  4. Public Class SingletonForm Inherits Form  
    
        Private Shared m_instance As SingletonForm  
    
         Private Sub New() 
         'InitializeComponent(); 
         End Sub 
    
         Public Shared ReadOnly Property Instance() As SingletonForm 
          Get 
           If m_instance Is Nothing Then 
            m_instance = New SingletonForm() 
           End If 
           m_instance.BringToFront() 
           Return m_instance 
          End Get 
         End Property 
        End Class 
    
    注:這是轉換爲vb.net,所以我不知道這是完美的
相關問題