zousijiu
zousijiu

Reputation: 11

How to open a Excel through C# and give the Excel focus

In my program, I want to open a Excel file and give the Excel focus.

I use process.Start() to do this, it works only the first time open an Excel, it launches Excel and give it focus.

but if I don't colse the first Excel or this is already an Excel opened in my system, and go back to my program, open another Excel, this time, the new opened Excel won't be brought to foreground and doesn't have the focus.

I tried to use Windows API to get the window and set the focus, but it threw an exception when open the second Excel :

process.MainWindowHandle = 'process.MainWindowHandle' threw an exception of type 'System.InvalidOperationException'

Can anyone help me with this ? Thanks in advance.

Upvotes: 0

Views: 1021

Answers (2)

Deanna
Deanna

Reputation: 24283

Rather than shelling to Excel directly, just specify your excel file as the filename and make sure it's set to use ShellExecute. This will load it in the same way as double clicking in Explorer. It also has the advantage of working with other excel viewers.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613311

Most likely you just need to call WaitForInputIdle before attempting to access MainWindowHandle. This will wait until Excel has started up sufficiently to have a main window handle allocated.

The other thing that now occurs to me is that Excel may be running out of a single process. So when you do Process.Start() the second time, what actually happens is that the second process hands the request on to the first process and then shuts down immediately. You could use task manager to test this hypothesis. If I'm right, then use Process.GetProcesses() to get the list of all running processes, find the Excel process, and give its main window the focus.

Upvotes: 1

Related Questions