Search code examples
c#visual-studioadd-inenvdte

Losing Window focus in own Visual Studio extension (using EnvDTE)


I'm writing a C# document outline extension for Visual Studio 2013.

The idea is to have a outline window and if the user clicks on a outline element the cursor jumps to the linked position in the code document. I'm using the EnvDTE.Document class to realise this:

DTE2 dte = GetService(typeof(DTE)) as DTE2;
var currentDocument = dte.ActiveDocument;

currentDocument.Activate();

var selection = (EnvDTE.TextSelection) CurrentDocument.Selection;
selection.MoveToLineAndOffset(line, offset);

I do the activation and selection change in a OnMouseDoubleClick event handler.

The issue is that at first the focus changes as intended but than my tool window gets the focus back. How do I prevent the focus from returning to the my tool window?


Solution

  • Found the solution!

    Actual Problem:

    The Issue was caused by the TreeView bubble behaviour. I.e. even if you handle the MouseDoubleClick event it bubbles up till the tree root element. My first level of TreeViewItems doesn't had my OnMousDoubleClick event handler connected. Therefore they reclaimed the focus once the event bubble reached them.

    Solution:

    Connect the OnMousDoubleClick handler to all TreeViewItem element in your tree and let all them call

    currentDocument.Activate();
    

    right at the beginning in the event handler - always.