Form focusing issue
Posted on 2009-12-23
I am working in Visual Studio 2008 .NET in C#, and I have 2 forms meant to be run concurrently. There is a grid in the first form and a TabControl on the 2nd form. When you change selected rows in the grid on the first form, it is going to cause one of the tabs on the 2nd form to become selected. I need this to happen without the grid on the first form losing focus.
Currently, the CellEnter event of the grid in form 1 is checking to see if the row changed. If so, it will call a method in form 2 that selects the required tab. Here's a sample of the code:
//In form 1
private void OnRowChange() //Called by CellEnter event, only if row changed
List<String> lstDocs = getDocIDList();
//Form2 is reference to form 2
//editingGrid is the DataGridView in the form
//In form 2
public void ViewLoadedDocs(List<String> pDocIDs)
int index = getFirstDocIndex(pDocIDs);
//docTabs is the TabControl on this form
This works most of the time and successfully restores focus to the DataGridView in form 1. However, and seemingly randomly, Form2 will remain focused after this function is called. Sometimes form 2 keeps focus after changing just one row in the grid, sometimes it's after changing a dozen rows. I have tried setting the focus in various different ways, setting it from ViewLoadedDocs instead of OnRowChange(), setting focus to form 1 itself instead of the grid, and selecting the tab in ViewLoadedDocs in differenet ways (changing SelectedIndex, etc). It will not occur if I do not select a tab in form 2, which is of course the only operation that would give form 2 focus.
Does anyone have any idea why form 1 would sometimes not maintain focus even after the Focus() method was called? Is the selection of the tab in form 2 happening on a separate thread somehow and sometimes executing after Focus() is called in form 1? If so, how can I prevent that? Is there a way to prevent form 2 from ever getting focus to begin with, but still change the selected tab in the TabControl?