2016-08-13 43 views
0

我有一個C#應用程序,它允許用戶記錄遊戲中發生的某些事件。爲了簡單起見,我會稱它們爲ParentFormChildFormC#在沒有新實例的表單之間傳遞的特定值

ParentForm 99%的時間用於記錄常見事件。這被表示爲用戶點擊PictureBoxTag屬性PictureBox被添加到ListBox。當發生「罕見」事件時,用戶可以點擊ParentForm上的「日誌罕見事件」按鈕以打開ChildForm,其打開一組「稀有事件」PictureBoxes,其功能與ParentForm中的功能相同。面臨的挑戰是,我希望將這些常見事件和罕見事件記錄到同一個ListBox,所以我試圖找出如何在上將PictureBox點擊(以及從此PictureBox開始的後續Tag)到ParentForm上的ListBox

ParentForm確實不是關閉,而ChildForm是開放的,需要保持開放。

ParentForm代碼,我已經捕捉到PictureBox點擊一個所需的代碼和抓住Tag,以及處理應對其添加到ListBox,所以這會是很好,如果我可以只使用這些。

這是我到目前爲止已經爲家長嘗試:

// This file is EventLogger.cs 
using rareEvent; 
namespace mainWindow { 
    public partial class EventLogger : Form { 
     // In the ParentForm (listeners for PictureBox clicks are handled elsewhere) 
     public void pictureBox_Click(object sender, EventArgs e) { 

      PictureBox pbSender = (PictureBox) sender; 

      // Open new window and handle "rare" drops 
      if (pbSender.Tag.ToString() == "rare") { 

       // Open rare form 
       EventLogger.RareForm rare = new EventLogger.RareForm(); 
       rare.Show(); 
      } 
     } 
    } 
} 

和這裏的孩子:

// This file is Rare.cs 
using EventLogger; 
namespace rareEvent { 
    public partial class rareEventForm : Form { 

     // In the ChildForm 
     private void pictureBox_Click(object sender, EventArgs e) { 

      // Does not compile if form is not instantiated, but I do not 
      // want a new instance 
      EventLogger form; 
      form.pictureBox_Click(sender, e); 
     } 
    } 
} 

我估計像這樣的工作,但它給人的錯誤

The type or namespace name 'EventLogger' does not exist in the namespace 
'mainWindow' (are you missing an assembly reference?) 

任何幫助將不勝感激。我發現的所有其他示例中的值之間傳遞的示例都似乎創建了新的實例,我不想要或8歲,並沒有工作。

欣賞它!

編輯:代碼更新爲每個文件中有using <namespace>。問題仍然存在,無法在之間使用new來發送值。 (見this回答評論)

+0

您必須使用實例在兩個窗體之間傳遞參數,但不需要關閉實例。請參閱以下發布的兩個表單項目。很多人都在使用我5年前開發的代碼。其他專家也推薦我的代碼:https://msdn.microsoft.com/en-us/library/w89fhyex(v=vs.110).aspx。我會很樂意回答任何其他問題。 – jdweng

+0

不確定你是否鏈接正確的東西 - 鏈接到套接字,沒有什麼說'兩個表單項目' – Sej

+0

你的正確。該鏈接是對TCP上不同發佈的迴應。這裏是正確的鏈接:http://stackoverflow.com/questions/34975508/reach-control-from-another-page-asp-net – jdweng

回答

1

在第一種形式創建一個實例(它)在這裏像我的form1。它必須是靜態的,所有你想訪問的數據類型都應該是公開的。

//FORM1 
public partial class Form1 : Form 
{ 
    //Instance of this form 
    public static Form1 instance; 

    //For testing 
    public string myProperty = "TEST"; 

    //Assign instance to this either in the constructor on on load like this 
    public Form1() 
    { 

     InitializeComponent(); 
     instance = this; 
    } 
    //or 
    private void Form1_Load(object sender, EventArgs e) 
    { 
     //Assign the instance to this class 
     instance = this; 
    } 

然後在form2中調用EventLogger.RareForm rare = new EventLogger。RareForm();而不是新的形式做

EventLogger.RareForm rare = EventLogger.RareForm.instance 

或者對於我來說

Form1 frm = Form1.instance; 

我再檢查形式1的財產窗口2像這樣

Console.WriteLine(frm.myProperty); 

輸出爲 「測試」

任何麻煩大喊。

+0

完美。 '實例'位是我需要的一切。非常感謝!! – Sej

+0

快樂回答我的第一個問題 –

+0

太棒了:) – Sej