pac w
pac w

Reputation: 657

C# Winforms form losing focus when focusing on child control ... sometimes

I am developing a windows mobile 6.5 app and have issues with my form losing focus when focusing on a child control of a UserControl added to the form... sometimes.

In my app I navigate between screens by adding and removing user controls to the main form controls collection.

IView nextView = (IView)Activator.CreateInstance(map.View);

this.Controls.Remove((UserControl)this.currentView);

this.currentView = nextView;

this.Controls.Add((UserControl)this.currentView);

My basic flow for navigation between screens is thus:

First add of UserControl A

  1. Initialize UserControl A
  2. Add UserControl A to Form.Controls
  3. Focus on grid on A

Navigate to UserControl B

  1. Initialize UserControl B
  2. Remove UserControl A from Form.Controls
  3. Add UserControl B to Form.Controls

Navigate back to UserControl A

  1. Initialize UserControl A
  2. Remove UserControl B from Form.Controls
  3. Add UserControl A to Form.Controls
  4. Focus on grid on A

All this works fine and on the first add of UserControl A the form is focused and the child control has focus as well.

But when I navigate back to UserControl A from UserControl B the form loses focus, but only if I try to focus on the child control in the last step. In my app this has the consequence that I cannot navigate in the grid using the phone hardware buttons.

Any idea on why the main form loses focus?

Upvotes: 3

Views: 2226

Answers (1)

pac w
pac w

Reputation: 657

Turns out that when I navigated back to UserControl A, which I do by triggering a navigation event in the middle of a method, the code in UserControl B continued to execute thereby preventing focusing on UserControl A.

I had hoped that when I removed UserControl B from Form.Controls (and then disposing it) the rest of the method wouldn't be executed, kind of like Response.Redirect does for web.

I solved the problem by adding a return; statement after triggering the OnNavigation event in UserControl B.

Upvotes: 2

Related Questions