Record Excel Macro Programatically - C#

Prateek Gupta 1 Reputation point
2021-03-02T09:39:58.083+00:00

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.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,670 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,234 questions
{count} votes