Search code examples
c#excelcominterop

How to keep Excel interop from stealing focus while inserting images


I'm using the Excel COM interop to insert images (specifically EPS) into a spreadsheet. The images are inserted fine, but Excel ignores all the visible/background settings and steals the focus the display a dialog box saying something like "importing image". The dialog box only stays a fraction of a section, but it makes the screen flicker, and worse, when I'm inserting many images at once, it can monopolize the system for several seconds (including stealing keystrokes from the foreground process).

I'm setting the background options as follows:

Excel.Application xlApp = new Excel.Application();
xlApp.Visible = false;
xlApp.ScreenUpdating = false;
xlApp.DisplayAlerts = false;
Excel.Worksheet worksheet;
//....
worksheet.Pictures(Type.Missing).Insert(filename,Type.Missing); //steals focus

How can I get Excel to stay in the background here like it belongs?


Solution

  • I suspect this is caused by a component that Microsoft licensed that is badly behaved.

    The only way to deal with situations like this is by intercepting the appropriate low-level Windows message and blocking it using a Win32 hook

    The easiest way to do this, and, believe me, it's not pretty, is to use the CBT hook. CBT stands for "Computer Based Training." It is an ancient and nearly obsolete technology intended to make it possible to create training apps which watch what you're doing and respond accordingly. The only thing it's good for any more is hooking and preventing window activation in code you don't have access to. You could intercept the HCBT_ACTIVATE code and prevent a window from activating.

    This would probably need to be done in C or C++.