views:

618

answers:

4

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?

+1  A: 

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.
Vinay Sajip
Thanks, tried this. Turns out, this 3rd party activex control steals the focus multiple times, usually 2 to 3 times, after the the call to DoSomething(). This complicates your above hackish solution. Thanks anyways.
Judah Himango
+1  A: 

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.

MusiGenesis
Yeah, pretty hackish. I tried this, and found the control itself steals the focus 2-3 times during this period, so even this hack doesn't work entirely.
Judah Himango
+1  A: 

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?

MusiGenesis
Afraid it has to be on our form. Ugh.
Judah Himango
+2  A: 

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?

Jewel S
Possibly. I'll try that and get back to you.
Judah Himango
I've given this a shot and it seems to work. Granted, it's a hack, but not too ugly, and works pretty consistently. Thanks for the suggestion, I'm marking this as the accepted answer.
Judah Himango