Judah Gabriel Himango
Judah Gabriel Himango

Reputation: 60021

How to prevent control from stealing focus?

We have a 3rd party control loaded in our C# WinForms app.

When we call a method on this 3rd party ActiveX control, it asynchronously steals focus. For example:

// This call causes 3rd party to spawn a thread and steal focus 
// milliseconds later.
foo3rdParty.DoSomething();

Is there a way to prevent a control from stealing focus?

Upvotes: 4

Views: 4968

Answers (4)

Jewel S
Jewel S

Reputation:

ugh. you've probably already thought of this but can you disable the control's window during the period (or a guesstimation) when it tries to take focus, without hurting the user experience?

Upvotes: 2

MusiGenesis
MusiGenesis

Reputation: 75296

If this evil little control isn't meant to be visible, you could place it on an invisible form and call DoSomething() on it there. Then, who cares if it grabs the focus?

Upvotes: 3

MusiGenesis
MusiGenesis

Reputation: 75296

If the control has a GotFocus() event (and it's correctly raised by the control whenever it steals the focus), you could attach a handler to that and set the focus back to the last control that had the focus (or the OK button or whatever).

This might produce weirdness if someone is typing in a textbox in the middle of this. My solution would be to give my money to someone who was willing to do maybe 15 minutes of work to help me.

Upvotes: 3

Vinay Sajip
Vinay Sajip

Reputation: 99355

You could try this rough approach:

  1. Find which control has focus before you make the call, say using Form.ActiveControl.
  2. Attach a handler to the active control which gets called when it loses focus.
  3. Make the call to the third-party control's method.
  4. If all goes as expected, the third-party control will gain focus, and the previously focused control will lose focus, and the handler will be called.
  5. In that handler, either set focus back to the previous control, or schedule some code to run on a thread to do so a little later.

Upvotes: 2

Related Questions