Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to prevent Form from loosing focus (in the application)

0.00/5 (No votes)
24 May 2010 1  
We all know that .ShowDialog() is great but sometimes You want to show user some window and keep program running. (.ShowDialog() freezes code execution in method as we all know) Let's say You have this scenario that You want to have form that will not loose focus but at the same time You...
We all know that .ShowDialog() is great but sometimes You want to show user some window and keep program running. (.ShowDialog() freezes code execution in method as we all know)

Let's say You have this scenario that You want to have form that will not loose focus but at the same time You want to do some work after window is shown. Of course .ShowDialog() is not an option because work after it will not be done before You close the window. So how can You acomplish this ?

I've searched on forums and some solution (especially with Deactivate/Activate) simply don't work. So how can You do this ?

In Your form class, override OnLostFocus(EventArgs e) and place focusing call inside it. So it looks like this:
C#
protected override void OnLostFocus(EventArgs e)
{
        base.OnLostFocus(e);
        this.Focus();
}


Simple but works. :-)


OK. In some cases (and i don't know exactly why) you should do

C#
protected override void OnDeactivate(EventArgs e)
{
        base.OnDeactivate(e);
        this.Focus();
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here