I wrote the following code to capture the click event of Excel's standard toolbar button activated in a C# application.
private void CaptureExcelInteractions()
{
Excel.Application excelApp = null;
// Get the process ID of the active window
IntPtr hwnd = GetForegroundWindow();
uint processId;
GetWindowThreadProcessId(hwnd, out processId);
try
{
// Enumerate running Excel processes
Process[] processes = Process.GetProcessesByName("EXCEL");
foreach (Process process in processes)
{
if (process.Id == (int)processId)
{
// This Excel process is the active one
excelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
break;
}
}
if (excelApp == null)
{
// No active Excel instance found
Console.WriteLine("No active Excel instance found.");
return;
}
}
catch (System.Runtime.InteropServices.COMException ex)
{
// Handle exceptions if Excel is not running or not accessible
Console.WriteLine("Excel is not running or not accessible. Error: " + ex.Message);
return;
}
// Reference the active worksheet
Excel.Worksheet activeWorksheet = (Excel.Worksheet)excelApp.ActiveSheet;
// Capture cell changes and subscribe to Excel
excelApp.SheetChange += (object sh, Excel.Range target) =>
{
string cellAddress = target.Address;
string newValue = (string)target.Text;
Console.WriteLine($"Cell {cellAddress} changed to: {newValue}");
};
// Get a reference to the CommandBars
foreach (CommandBar commandBar in excelApp.CommandBars)
{
foreach (CommandBarControl control in commandBar.Controls)
{
if (control is CommandBarButton button)
{
button.Click += (CommandBarButton ctrl, ref bool cancelDefault) =>
{
string buttonName = ctrl.Caption;
Console.WriteLine($"CommandBarButton clicked: {buttonName}");
};
}
}
}
// Keep this method running to capture events
while (isMonitoring && !isPaused)
{
// Add a delay or use other mechanisms to keep the method running
Thread.Sleep(1000);
}
Marshal.ReleaseComObject(excelApp);
// Stop Excel event handling
excelApp.Quit();
}
However, although the standard toolbar is found, the click event is not executed. This is not an Excel add-in, but a button click event on the existing toolbar. What did I do wrong?
For example, when I click the "Bold" CommandBarButton on the "Font" toolbar, I expect console output to appear, but the click event is not detected.