问题
I have form A, which opens form B after an event then hides itself. Form B generates conditions for form A then returns to form A and closes itself; however, due to conflict with code, I will have to generate form A anew lest I encounter a stackoverflow exception / my application not closing properly (due to form A, the main form, being hidden)
This has gotten a bit confusing, essentially I've already solved this by declaring the main form as new each time, however, I wish to be able to handle first time startup events like those tutorial messages for certain applications. Without the overhead of having to create a log to store my boolean, how will I detect if it's the first time the form is opened?
Normally I would:
Event(){
bool startup;
if (startup = true) {
startup = false;
return;
}
//Rest of code
}
However, since the form is generated new each time, this will always remain true.
Here's the code:
Form A variables:
Account AccountForm = new Account();
Button event:
AccountForm.QR = this;
this.Hide();
AccountForm.ShowDialog();
Form B:
public Form QR { get; set; }
Button event:
QR = new QueryRefiner();
this.QR.Show();
this.Close();
This is all of it I think. I take the new declaration out of QR, and I would receive a StackOverflow exception. I guess I should have created a new question for this, but there it is. (I think i'm on the timer still)
回答1:
Well,an easy solution is to make a new constructor in your FormA to get a parameter indicating that it is created from FormB, something like:
public FormA(bool byFormB)
{
if (byFormB)
{
//do what you have to do when it's created from FormB
}
}
And just create it like this from FormB: FormA frm=new FormA(true);
Anyway, I would not create a new FormA each time, just hide/show it.
回答2:
Here's one way to do it: Expose a public property in your FormB that holds a reference to a FormA. When you create an instance of FormB from FormA, set the reference to point to FormA. Then, in the Form_Closing() event of FormB, show the FormA.
You can also expose public properties and/or methods on your FormA so that FormB can pass on any information it gathered back to FormA before it exits:
public partial class FormB : Form
{
public FormA formToShowOnClose { get; set; }
private void FormB_FormClosing(object sender, FormClosingEventArgs e)
{
if (formToShowOnClose != null)
{
formToShowOnClose.TableName = txtTableName.txt;
formToShowOnClose.LoadData();
formToShowOnClose.Show();
}
}
// Other form B code here...
}
public partial class FormA : Form
{
public string TableName { get; set; }
public void LoadData()
{
// Do something with TableName here
}
private void button1_Click(object sender, EventArgs e)
{
var formB = new FormB();
formB.formToShowOnClose = this;
this.Hide();
formB.Show();
}
// Other form A code here...
}
来源:https://stackoverflow.com/questions/43446753/c-sharp-how-do-i-handle-a-one-time-startup-condition-for-a-form-if-the-form-is-g