Apr 192013
 

I’m writing a plugin in .NET that’s hosted on a windows service running in the background. There I want to display a WPF modal window that should be activated and stay on top as soon as it gets shown. This is the only way I found that worked for me:

using System;
using System.Threading;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Interop;
using System.Windows.Threading;

public static class UiHelper
{
    public static void ShowDialogInNewThread<T>(object dataContext, Action<T> onComplete) where T : Window, new()
    {
        Thread thread = new Thread(() =>
        {
            SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher));
            var window = new T();
            window.DataContext = dataContext;
            window.Closed += (s, e) => Dispatcher.CurrentDispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
            window.Show();

            IntPtr handle = new WindowInteropHelper(window).Handle;
            AutomationElement element = AutomationElement.FromHandle(handle);
            if (element != null)
            {
                element.SetFocus();
            }

            System.Windows.Threading.Dispatcher.Run();
            onComplete(window);
        });

        thread.SetApartmentState(ApartmentState.STA);
        thread.IsBackground = true;
        thread.Start();
        thread.Join();
    }
}

 Posted by at 2:50 pm