如何从form1中的新表单传递/检测按钮单击事件?

时间:2017-03-21 21:57:22

标签: c# .net winforms

以新形式:

private void btnOK_Click(object sender, EventArgs e)
        {
Properties.Settings.Default.AddNewDownloadsUrl = TextBoxURL.Text;
Properties.Settings.Default.AddNewDownloadsFilename = TextBoxFilename.Text;
Properties.Settings.Default.AddNewDownloadsSaveto = TextBoxBrowse.Text;
Properties.Settings.Default.Save();
        }

在Form1中

private void btnAddNewDownload_Click(object sender, EventArgs e)
        {
            AddNewDownloads addnew = new AddNewDownloads();
            addnew.Show();
        }

现在我希望当我点击新表单中的btnOK按钮以获取form1中的所有Properties.Settings.Default时。我是否还需要以某种方式在form1中制作btnOK点击事件?我想要的只有当我点击btnOK并在它保存设置然后在form1中才能获得此设置。问题是当我点击btnOK

时我不知道form1

2 个答案:

答案 0 :(得分:1)

以下是在btnOK表单上点击AddNewDownloads时在Form1中引发事件的代码。因此,当Form1知道点击btnOK时,您的问题就解决了。我使用记事本编写代码,所以尝试下面的代码,让我知道它是否有效。我将重新访问Visual Studio中的代码。

//--------------Form1 code

//declaring addnew object as class level or Method level depends on your design
//I prefer declaring class level as we can access addnew object properties
//from anywhere in Form1
AddNewDownloads addnew;

private void btnAddNewDownload_Click(object sender, EventArgs e)
{
    if (addnew == null)
    {
        addnew = new AddNewDownloads();
        addnew.BtnOkClicked += addnew_BtnOkClicked;
    }

    addnew.Show();
}

private void addnew_BtnOkClicked(object sender, EventArgs e)
{
    //place your code here to 
    MessageBox.Show("Event raised by Ok button in AddNewDownloads");

}



//----------------------AddNewDownloads code
//declare a class level event
public event EventHandler BtnOkClicked;

private void btnOK_Click(object sender, EventArgs e)
{
    //This will fire an event to be caught by subscriber
    //which is Form1.. put a break point in 
    OnGotClosed(EventArgs.Empty);

    //I am not sure where yo want to put Properties.Settings
    //So removed it from here... but you can decide and put 
    //as per your design
}

protected virtual void OnBtnOkClicked(EventArgs e)
{
    EventHandler handler = BtnOkClicked;
    if (handler != null)
    {
        handler(this, e);
    }
}

答案 1 :(得分:0)

  1. AddNewDownloads表单上选择表单属性,并将btnOK分配给AcceptButton属性。当您单击按钮时,这会将DialogResult.OK分配给表单的DialogResult属性。
  2. 使用addnew.ShowDialog()代替简单Show()
  3. 验证ShowDialog()来电的返回值。
  4. Form1的代码:

    private void btnAddNewDownload_Click(object sender, EventArgs e)
    {
        using(var addnew = new AddNewDownloads())
        {
           if (addnew.ShowDialog() != DialogResult.OK)
              return;
    
           // get settings here
        }
    }