Reputation: 129
I have Form1 in my application calling another form - Form2 using ShowDialog() method. After some user interaction Form2 calls its Hide() method. After that my application sometimes loses focus sometimes not. It could be some design mistake.
code extract:
public class Form1 : Form
{
Form2 form2;
public void SomeMethod()
{
if (form2==null) form2 = new Form2();
DialogResult result = form2.ShowDialog(this);
}
}
public class Form2 : Form
{
public Form2()
{
this.FormClosing += new FormClosingEventHandler(Form2_FormClosing);
}
void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
Hide();
}
}
}
edit: I had mistake in my code on line
DialogResult result = form2.ShowDialog(this);
was
DialogResult result = ShowDialog(form2,this);
Upvotes: 2
Views: 3583
Reputation: 11
private: System::Void form_closing(System::Object^ sender, CancelEventArgs^ e) {
MessageBox::Show( "Ulosteministeri Katainen" );
e->Cancel = true;
form->Hide();
this->Focus();//this is the parent form
}
Upvotes: 1
Reputation: 82096
If you hide the dialog box then Form1 will still be inaccessible as ShowDialog requires you to close it before it gives focus back.
Only handle the closing of Form2 if you intend to do something with it. Otherwise just let the dialog close there is no benefit to hiding it.
See MSDN Form.ShowDialog for more details.
Code Sample
public class Form1: Form
{
private Form2: form2;
private bool doDbQuery;
public Form1()
{
doDbQuery = true;
}
public void SomeMethod()
{
if (form2 != null)
{
form2 = new Form();
}
if (doDbQuery)
{
// do DB query
// take a note of the information you retrieve
doDbQuery = false;
}
// pass this information to Form2 for it to display.
DialogResult result = form2.Execute(...);
}
}
public class Form2 : Form
{
public Form2()
{
}
public DialogResult Execute(...)
{
// use the execute method to inject the data you require for the form
return ShowDialog;
}
}
Upvotes: 2
Reputation: 28586
if you use some "lazy" functions, you can use the asynchronous methods, at the end of what to close your form(Delegate Callbacks).
Upvotes: 0