views:

108

answers:

2

I have a form that pops up on a user's screen and has TopMost=true, but it steals the focus. How can I get it to not steal focus when it first appears?

+2  A: 

Paste this code in your form:

protected override bool ShowWithoutActivation
{
    get { return true; }
}
Hans Passant
It does not work in VS2008 when TopMost is set to True. I will try it on VS2010 now.
François
Still doesn't work in VS 2010. Only works when TopMost on the popup form is set to false.
François
I'm using VS2008 and it worked perfectly :)
Soo
Oh rats, that's true, TopMost messes this up. Won't work in VS2010 either. You'll have to P/Invoke SetWindowPos() with HWND_TOPMOST and SWP_NOACTIVATE. Use pinvoke.net for the declarations.
Hans Passant
@Soo: Not sure how you got it to work as it is a well known bug. @Hans: +1 on the comment adding the mentioning of P/Invoke to solve that issue.
François
A: 

I tested the below code using a timer on form1 to instantiate and show form2 with form1 as owner.

In form2's Shown event I then set focus to the owner, which is the current active form.

I have a textbox on form1 and was able to continuesly write in the textbox without loosing focus during this process.

My timer code in form1:

private void timer1_Tick(object sender, EventArgs e)
{
    Form2 popup = new Form2();
    popup.TopMost = true;
    popup.Show(this);
    timer1.Enabled = false;
}

My code in the Shown event of form2:

private void Form2_Shown(object sender, EventArgs e)
{
    this.Owner.Focus();
}

You can do this or simply set TopMost to false and use the override of ShowWithoutActivation as Hans Passant stated.

Edit: (Or use p/invoke as seen in Hans Passant's additional comment I missed while I wrote this)

François