views:

402

answers:

2

Hi there.

I have a bit of an odd question. My situation is as following:

I have a form, It contains several user controls that in turn contains either other user controls or other basic controls such as TextBox, RichTextBox and such.

As part of the logic when editing the text boxes, I create another control programatically and inform the form about it. Other controls on the form may react in turn and create more controls.

Trouble is, These controls steal focus from my control when they are created and added to the form/other controls.

Is there a way to prevent my control from losing focus while that happens?

+1  A: 

Maybe you should include in the logic, the tab indexes first, and when you add the control, set the tab index to the last tab index + 1, your job would be easier, if you set the tab order first on the controls, and set the constant to the last tab index at design time, see here,:

private const int LAST_TAB_INDEX = 5; // an Example
private int lastTabIndex = LAST_TAB_INDEX; 

private void AddControl(){
   // Set up your control
   Control ctl = new Control();
   // ....
   ctl.TabIndex = lastTabIndex;   
   this.Add(ctl);
   this.lastTabIndex++;
}

You can see from the example how the tab index is incremented, in that way, it will prevent the controls from stealing the focus...

Hope this helps, Best regards, Tom.

tommieb75
A: 

Controls can't accept (steal) focus unless they are visible and enabled. Have you tried creating the controls with one or both of these as false, and then turning them on when appropriate?

cmsjr
Thought of that, Even went as far as reflecting the .NET assmblies to see what CanFocus/Focus check for (even though MSDN states what), But this didn't seem to help in all cases, and i sometimes needed to make the control visible anyway.Anyway, I'll mark this as the answer since this is probably the closest thing there is. My case seems to be more delicate and ill play around with this and see.Thanks.
Ran Sagy