简体   繁体   English

如何从不同的表单访问按钮按下? C#

[英]How can I access a Button Press from a different Form? C#

So I am creating a Text Editor, and I want to have a popup when the user attempts to close the application asking whether they are sure they want to do this, much like in Windows' Notepad.所以我正在创建一个文本编辑器,当用户尝试关闭应用程序时,我希望有一个弹出窗口,询问他们是否确定要这样做,就像在 Windows 的记事本中一样。 I am not using MessageBoxes, but instead am using a custom Form.我没有使用 MessageBoxes,而是使用自定义表单。 How can I get the info from the Button they press in Form2 and access it in Form1?如何从他们在 Form2 中按下的按钮获取信息并在 Form1 中访问它?

Thanks in advance for the responses.预先感谢您的答复。 If there's any other info I can provide that would be useful, please let me know!如果我可以提供任何其他有用的信息,请告诉我!

Edit as to what I mean: I have created a form with 3 buttons: Save, Don't Save, and Cancel.编辑我的意思:我创建了一个带有 3 个按钮的表单:保存、不保存和取消。 I want to get the info as to what they've pressed.我想获得有关他们按下了什么的信息。 Would I simply get the return of the button and go from there?我会简单地得到按钮的返回并从那里开始吗?

You need to have a property to pull the info out of on the secondary form.您需要有一个属性来从辅助表单中提取信息。 You'll still want to use ShowDialog() and then you can check the dialog result.您仍然需要使用 ShowDialog() 然后您可以检查对话框结果。 This is from memory so the code may not build, but should give you the idea.这是来自记忆,所以代码可能无法构建,但应该给你这个想法。

On your Form2在您的 Form2 上

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();
}

On your other Form1在您的另一个 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
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM