0

I am developing an Excel Office Addin in which I am using WPF form, I was able to create a form and show it on button click with the help of the below code

UC frm = new UC();
ElementHost.EnableModelessKeyboardInterop(frm);
frm.Show();
System.Windows.Threading.Dispatcher.Run();

I made the Window to be TopMost so that when I select a range in Excel, I want the address to be coming in WPF text box. What is happening is when I open the form and if I go and select the Excel range, the focus is not going back to Excel application and SelectionChange event is not triggered.

if I remove this line System.Windows.Threading.Dispatcher.Run(); it works but I don't get focus on WPF form(not able to enter anything on the form textbox) when I enter it always gets to Excel cell

Can some please please help in switching focus here

Sam K
  • 332
  • 1
  • 6
  • 19

1 Answers1

0

I figured it out by using this code

var thread = new Thread(() =>
{
mw = new UI.MainWindow();
mw.Show();
mw.Closed += (sender2, e2) => mw.Dispatcher.InvokeShutdown();
Dispatcher.Run();
});

thread.SetApartmentState(ApartmentState.STA);
thread.Start();
Sam K
  • 332
  • 1
  • 6
  • 19
  • Sorry to hijack this 4 years later! I have an addin that is doing something very similar, However, on the newer version of Excel having the window on the separate thread means Excel has a hanging process. The side effect of this is that the next time Excel opens it takes ages and then disables the add-in. Have you had this issue? – theJ Jan 12 '23 at 12:20