Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block on a OpenFile in a Visual Studio addin

I have a Visual Studio 2008 addin that when I press a certain hotkey, it opens a specific file (different based on the context of the hotkey) and then searches that file for a specific string (again, context dependent.) Most of the time this works flawlessly, but sometimes if the file it's opening is too big, the search will fail.

Here is a code snippet:

Window xmlWindow = Commands.Application.ItemOperations.OpenFile(objectFilename, EnvDTE.Constants.vsViewKindPrimary);
Find find = xmlWindow.Document.DTE.Find;
find.Action = vsFindAction.vsFindActionFind;
find.FindWhat = String.Format("Name=\"{0}\"", objectLocalName);
if (find.Execute() == vsFindResult.vsFindResultFound) {
     MessageBox.Show("Found!");
}



1. Is there a way to get it to always work (for example by blocking on the OpenFile)?

2. On a less important note, is there a way to search like this without having the results end up in the Find Results pane (this causes my old results to be cleared out by this search that is only used to get the cursor down to that part of the file)?


like image 814
Daniel Jennings Avatar asked Dec 23 '22 01:12

Daniel Jennings


1 Answers

If OpenFile behaves asynchronously, I'd suggest you consider changing the logic to rely on a different event, one that relies on the document being activated.

For example, have you tried triggering the OpenFile with your shortcut key, then queuing the search so that it's later handled by a VS event? (The code below was taken from a Visual Studio 2010 addin, but I believe the events are the same.)

// make sure these are class variables, otherwise they may get GC'd incorrectly and break the COM interaction private WindowEvents _winEvents = null; private DTE2 _applicationObject;

in the connect:

_events = _applicationObject.Events;
_winEvents = _events.get_WindowEvents();

_winEvents.WindowActivated += new _dispWindowEvents_WindowActivatedEventHandler(WindowActivated);

Then, you'd put some code in the WindowActivated:

void WindowActivated(Window GotFocus, Window LostFocus)
        {
            Document gotFocusDoc = GotFocus.Document;
            if (gotFocusDoc != null)
            {
                string fileExt = Path.GetExtension(gotFocusDoc.Name);

There, you'd watch for the file that you wanted to scan (you'd maybe need to keep a list, etc.).

For the second issue, you could just scan through the document yourself once you've got access in the way I suggested above.

like image 139
WiredPrairie Avatar answered Jan 03 '23 00:01

WiredPrairie