private Project GetSelectedProject(IServiceProvider provider)
{
// Get the DTE service and make sure there is an open solution
DTE dte = provider.GetService(typeof(DTE)) as DTE;
if (dte == null || dte.Solution == null)
{
return null;
}
Project project = null;
IntPtr selectionHierarchy = IntPtr.Zero;
IntPtr selectionContainer = IntPtr.Zero;
// Get the current selection in the shell
IVsMonitorSelection monitorSelection = provider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection;
if (monitorSelection != null)
{
try
{
uint itemId;
IVsMultiItemSelect multiSelect;
monitorSelection.GetCurrentSelection(out selectionHierarchy, out itemId, out multiSelect, out selectionContainer);
if (selectionHierarchy != IntPtr.Zero)
{
IVsHierarchy hierarchy = (IVsHierarchy)Marshal.GetObjectForIUnknown(selectionHierarchy);
return GetProjectFromHierarchy(hierarchy);
}
}
catch (Exception)
{
return null;
}
finally
{
// Make sure we release the COM pointers in any case
if (selectionHierarchy != IntPtr.Zero)
{
Marshal.Release(selectionHierarchy);
}
if (selectionContainer != IntPtr.Zero)
{
Marshal.Release(selectionContainer);
}
}
}
return null;
}