A problem I have encountered from time to time is how to detect whether or not there is a shape selected in Excel. The problem is that the Excel object model does not fire the WindowsSelecitonChange event if and when the user clicks on a shape. So one of the workarounds out there today is to hook to the CommandBars.OnUpdae event and then look to see if one f the commands associated with Shapes is enabled, like ShapeFillColorPicker. The problem I have found is that this method worked in Excel 2007 and Excel 2010, but it stopped working or began working intermittently for me in Excel 2013. So, I had to develop a bit of a workaround to this problem – which also works still in Excel 2010 and Excel 2007 and to the best I can tell causes no impact to performance in Excel. I start a thread, have it sleep for a short time, hook and then unhook the OnUpdate event and then DoEvents for good measure. Like this:
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
new Thread(() =>
{
while (true)
{
Thread.Sleep(25);
Application.CommandBars.OnUpdate -= CommandBars_OnUpdate;
Application.CommandBars.OnUpdate += CommandBars_OnUpdate;
System.Windows.Forms.Application.DoEvents();
}
}).Start();
}
void CommandBars_OnUpdate()
{
try
{
if (Application.CommandBars.GetEnabledMso("ShapeFillColorPicker"))
{
// A Shape was selected
}
}
catch { }
}