I have written an application which has a modal form. How can I ensure that this form does not lose the focus even when an other application is started?
Actually, this is exactly the sort of thing you shouldn't be doing.
There's too many programs around that assume they control the computer they're installed on. It is the user of your application that should be in control.
That's why later versions of Windows disallowed stealing of focus instead insisting on just blinking the entry in the task list bar.
You may well find a way to do it (though I doubt it), but I urge you to rethink it. I'd be interested in knowing why you thought it was necessary.
You can set the "Topmost" property to true to keep the form in front of all others but that doesn't make it keep focus.
I use
SetForegroundWindow(Me.Handle)
Me.Handle is the handle of your form.
You need to declare the following somewhere in your class or winform, but not inside a function
Declare Unicode Function SetForegroundWindow Lib "user32.dll" (ByVal hWnd As IntPtr) As Boolean
You might need to initiate a timer and call SetForegroundWindow on every tick of say 10 seconds, depending on your preference.
EDIT: It works for me, if it doesn't add the following
Declare Unicode Function SystemParametersInfo Lib "user32.dll" Alias "SystemParametersInfoW" (ByVal uiAction As Int32, ByVal uiParam As Int32, ByRef pvParam As Int32, ByVal fWinIni As Int32) As Int32
And surround SetForegroundWindow with these
Dim _timeout As Int32
SystemParametersInfo(&H2000, 0, _timeout, 0)
SystemParametersInfo(&H2001, 0, 0, 3)
SetForegroundWindow(Me.Handle)
SystemParametersInfo(&H2001, 0, _timeout, 2)
That's the last resort
I have to use an application that grabs focus when it pops up an alarm. I hate it! (If I had any choice, I would not use the damn thing; sadly, I have to use it. Ugh!) Other parts of the program are far too keen on maintaining focus. Some forms do not let you cut'n'paste text from other pages. It is an abomination when a program does that. If you want your software used by people who have a choice, then DO NOT grab and retain focus.