2015-06-14 112 views
1

所以我創建了一個文本編輯器,當用戶嘗試關閉應用程序時詢問他們是否確實想要這樣做,這很像在Windows'記事本中。我沒有使用MessageBoxes,而是使用自定義窗體。我如何從Form2中按下的按鈕獲取信息並在Form1中訪問它?如何從不同的表單訪問按鈕按鈕? C#

在此先感謝您的回覆。如果有任何其他信息我可以提供,這將是有用的,請讓我知道!

編輯我的意思:我創建了一個帶有3個按鈕的表單:保存,不保存和取消。我想獲得他們所按的信息。我只需要返回按鈕並從那裏出發?

+0

使用'的ShowDialog()'和評估返回 – Plutonix

+0

請解釋一下你的意思是「得到他們按下按鈕的信息」。你想獲得什麼信息?如果確定用戶是否點擊是或否,那麼Plutonix就有正確的想法。 –

回答

1

您需要有一個屬性才能將信息從輔助表單中提取出來。你仍然想使用ShowDialog(),然後你可以檢查對話框的結果。這是來自內存,所以代碼可能不會構建,但應該給你這個想法。

在你的窗體2

public string Text 
{ 
    get { return this.SomeTextBoxOnTheForm.Text; } 
    set { this.SomeTextBoxOnTheForm.Text = value; } 
} 

//called from your "Save" button. 
public void Save() 
{ 
    this.DialogResult = DialogResult.Ok; 
    this.Close(); 
} 

//called from either your "DontSave" button or your "Cancel" button. 
public void Cancel() 
{ 
    this.DialogResult = DialogResult.Cancel; 
    this.Close(); 
} 

在你的其他Form1中

public void ShowForm2() 
{ 
    var form = new Form2(); 

    //you could even set default text here 
    form.Text = "Enter a message..."; 

    var result = form.ShowDialog(); 
    if(result == DialogResult.Ok) 
    { 
     var finalText = form.Text; 

     //do something with the text 
    } 
}