Click here to Skip to main content
15,887,428 members
Articles / Programming Languages / C#
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
3.33/5 (8 votes)
24 May 2010CPOL 48.1K   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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Agilion Consulting
Poland Poland
I specialize at C#, developing Enterprise solutions. I have some knowledge of ASP.NET MVC - looking forward to use it together with Typescript.

Comments and Discussions

 
-- There are no messages in this forum --