How can I stop Excel from losing focus while embedded using SetParent?

143 views Asked by At

I am trying to embed Excel inside a WPF application.

I've got all the stuff I need working already, except that now I am trying to allow .xlsm files. When clicking on ActiveX controls, it seems like the Excel loses focus, and I can no longer click on anything within the workbook.

I can still click on the Excel application UI such as the tabs and stuff. How can I prevent this focus change, or how can I get it back?

Here is a small sample of what I'm currently doing while opening Excel:

[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

if (excelApp == null)
    return;

if (!(windowsFormsHost1.Child is Panel panel))
{
    panel = new Panel();
    windowsFormsHost1.Child = panel;
}

excelHandle = new IntPtr(excelApp.Hwnd);
SetParent(excelHandle, panel.Handle);
SetForegroundWindow(excelHandle);
SetFocus(excelHandle);

I haven't tried changing much, as I wasn't really sure where to go from there. I have tried adding code to refocus Excel on a timer, but it doesn't fix anything.

I also had this issue when opening a new workbook originally, where I couldn't click on any cells or anything, and I had to create a new Excel application instance every time I opened a workbook. I can't really do that while the workbook is open.

0

There are 0 answers