How to switch focus between parent application and WPF forms?

92 views Asked by At

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

1

There are 1 answers

1
Sam K On BEST ANSWER

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();