views:

431

answers:

2

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?

A: 

I'm not sure I have a good answer to your question (I would have left a comment, but apparently I don't have enough reputation yet), but in case it's helpful, I often also disable events

xlApp.EnableEvents = False

Obviously you have to be sensitive to this setting when you're relying on Excel events in your code, but just in case there are some unwanted events firing while you're inserting, this might help.

Good luck!

TimS
+3  A: 

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++.

Joel Spolsky