/// <summary> /// This is used to get the content of a specific topic file if it is open in an editor so that the /// current content is displayed for it in the topic previewer control. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void ucTopicPreviewer_TopicContentNeeded(object sender, TopicContentNeededEventArgs e) { TopicEditorWindow topicEditor; foreach (IDockContent content in this.DockPanel.Documents) { topicEditor = content as TopicEditorWindow; if (topicEditor != null && topicEditor.Filename.Equals(e.TopicFilename, StringComparison.OrdinalIgnoreCase)) { e.TopicContent = topicEditor.FileContent; } } }
/// <summary> /// This is used to get the content of a specific topic file if it is open in an editor so that the /// current content is displayed for it in the topic previewer control. /// </summary> /// <param name="sender">The sender of the event</param> /// <param name="e">The event arguments</param> private void ucTopicPreviewer_TopicContentNeeded(object sender, TopicContentNeededEventArgs e) { ThreadHelper.ThrowIfNotOnUIThread(); IVsPersistDocData persistDocData; IVsTextStream srpStream; IntPtr docData = IntPtr.Zero; uint cookie = 0; int hr = VSConstants.E_FAIL; IVsRunningDocumentTable rdt = Utility.GetServiceFromPackage <IVsRunningDocumentTable, SVsRunningDocumentTable>(true); if (rdt == null) { return; } try { // Getting a read lock on the document. This must be released later. hr = rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, e.TopicFilename, out IVsHierarchy hier, out uint itemid, out docData, out cookie); if (ErrorHandler.Failed(hr) || docData == IntPtr.Zero) { return; } persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData; // Try to get the Text lines IVsTextLines srpTextLines = persistDocData as IVsTextLines; if (srpTextLines == null) { // Try getting a text buffer provider first if (persistDocData is IVsTextBufferProvider srpTextBufferProvider) { hr = srpTextBufferProvider.GetTextBuffer(out srpTextLines); } } if (ErrorHandler.Succeeded(hr)) { srpStream = srpTextLines as IVsTextStream; if (srpStream != null) { if (srpStream is IVsBatchUpdate srpBatchUpdate) { ErrorHandler.ThrowOnFailure(srpBatchUpdate.FlushPendingUpdates(0)); } hr = srpStream.GetSize(out int lBufferSize); if (ErrorHandler.Succeeded(hr)) { IntPtr dest = IntPtr.Zero; try { // GetStream() returns Unicode data so we need to double the buffer size dest = Marshal.AllocCoTaskMem((lBufferSize + 1) * 2); ErrorHandler.ThrowOnFailure(srpStream.GetStream(0, lBufferSize, dest)); // Get the contents e.TopicContent = Marshal.PtrToStringUni(dest); } finally { if (dest != IntPtr.Zero) { Marshal.FreeCoTaskMem(dest); } } } } } } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } if (cookie != 0) { ErrorHandler.ThrowOnFailure(rdt.UnlockDocument((uint)_VSRDTFLAGS.RDT_ReadLock, cookie)); } } }