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?
views:
108answers:
2
+2
A:
Paste this code in your form:
protected override bool ShowWithoutActivation
{
get { return true; }
}
Hans Passant
2010-09-16 19:31:22
It does not work in VS2008 when TopMost is set to True. I will try it on VS2010 now.
François
2010-09-16 19:49:44
Still doesn't work in VS 2010. Only works when TopMost on the popup form is set to false.
François
2010-09-16 19:56:28
I'm using VS2008 and it worked perfectly :)
Soo
2010-09-16 19:58:24
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
2010-09-16 19:59:45
@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
2010-09-25 00:17:12
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
2010-09-16 20:04:02