Modeless Dialog calls Modal Dialog. Hide causes application to lose focus.

T

Tom Clement

Hi everyone,
I need some help on a problem I'm seeing. Some very simple code causes the
current application to lose focus. It looks to me like a fundamental
WinForms bug, but perhaps I'm missing something. Here's the
easy-to-reproduce situation.

1. Bring up an application (Form1). Switch focus to another application
(Outlook for example), then back to Form1.
2. A winforms main form (Form1) calls a modeless dialog (Form2) using the
following code:
private void button1_Click(object sender, System.EventArgs e) // Form1.cs
{
Form2 frm = new Form2();
frm.Owner = this;
frm.Show();
}
3. Form2 calls a modal dialog using the following code: //
Form2.cs
private void button1_Click(object sender, System.EventArgs e)
{
Form2 frm = new Form3();
frm.ShowDialog();
}
4. Close Form3 using the close box (or by calling .Close()).
5. Hide Form2 using the following code:
// Form2.cs
private void button2_Click(object sender, System.EventArgs e)
{
this.Hide();
}
At this point, Outlook will have focus and Form1 will be hidden behind it.
You can see this at design time where VS.NET will get focus. Can someone
give me some help understanding what's going on here? Have I missed
something in the documentation (or these newsgroups) that would explain it?

Tom Clement
Apptero, Inc.
 
C

Chris Botha

I had my share of problems with this, and this is what I'm doing, there may
be more elegant solutions.
Declare the function,

Private Declare Function SetForegroundWindow Lib "user32" Alias
"SetForegroundWindow" (ByVal hwnd As Integer) As Integer

then call it after the action that hides the app,

SetForegroundWindow(Me.Handle.ToInt32)
 
T

Tom Clement

Thanks Chris, It's reassuring that I'm not nuts here ;)

I'm able to work around the problem using:
this.Owner.Focus();
this.Hide();
instead of just the Hide() call.

But I guess my real question is whether I'm misunderstanding something, or
Microsoft has a pretty fundamental bug... Any thoughts?

Tom Clement
Apptero, Inc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top