0

I am facing a issue while using WPF splash screen on a Windows Form. My splash screen is a WPF user control which is hosted on a ElementHost inside a standard Windows Form.

When I add ElementHost control to the Windows Form (programmatically or using form designer), I get the error as ‘The calling thread must be STA, because many UI components require this.’

private static SplashWindow _Form;
private static ManualResetEvent _manualResetEvent = new ManualResetEvent(false);

[STAThread]
static void Main(string[] args)
{    
    //Show the Splash window here
    Task.Run(() =>
          {                
                    try
                    {                    
                        _Form = new SplashWindow();
                        Application.Run(_Form);                    
                    }
                    catch (Exception e)
                    {
                        //throw exception of type loadException
                        _manualResetEvent.Set();
                    }
           });
    
            //Wait until the splash window is loaded
            _manualResetEvent.WaitOne();
            if (loadException != null)
            {
                // quit or throw exception        
            }
    
             splashForm.Invoke(() =>
             {
                var host = new System.Windows.Forms.Integration.ElementHost(); // ** FAILS HERE **              
                host.Dock = DockStyle.Fill;
                _Form.Controls.Add(host);
                _Form.Show();
              });
    
}

When I remove ElementHost, and use any other control, then Windows Form (Splash Screen Form) gets shown!

  • Because Task.Run runs the Action on a background thread. Besides that, when you use it, you must await the call. – Clemens Apr 20 '22 at 07:37
  • why does this problem only comes for ElementHost and not for any other controls when placed inside Windows Form. ElementHost is essential to my use case as I need to reuse WPF controls – CodingLearner Apr 20 '22 at 08:45
  • Best to ask at superuser.com. Also: https://www.biztalk360.com/blog/biztalk-server-tips-and-tricks-configure-visual-studio-to-run-with-elevated-permissions-as-administrator – Hans Passant Apr 20 '22 at 12:35

0 Answers0