I am trying to record macros in excel application via C# WPF application. After running the application, while moving focus to excel application, the macro should start, and while switching to some other application, the macro recording should stop.
I have tried implementing it using
focusHandler = new AutomationFocusChangedEventHandler(OnFocusChanged); Automation.AddAutomationFocusChangedEventHandler(focusHandler);
This helps in detecting focus change on application. Then after filtering application type as excel, I am using the following to start macro in excel using interop:
var macroStartButton = excelApp.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton, 184); macroStartButton.Execute();
Then again when focus changes to other application, using the following to stop macro recording:
macroStopButton = excelApp.CommandBars.FindControl(Microsoft.Office.Core.MsoControlType.msoControlButton, 2186); macroStopButton.Execute();
The above approach is working intermittently. Can someone suggest a better approach or changes to current approach.