0

am doing a project in wpf. i navigate from a window to a form and when i navigate to another window it generate the following error. thanks in advance.

The calling thread must be STA, because many UI components require this

verificationform.cs

if (result.Verified)
            {
                MakeReport("The fingerprint was VERIFIED.");
                Home h = new Home();
                this.Hide();
                h.Show();
            }

==========================================================

public partial class Home : Window
{
    public Home()  ////######error occurs here!!!
    {

        InitializeComponent();
        labelNAME.Content = (string)Application.Current.Properties["name"];
    }
}
Tudor
  • 61,523
  • 12
  • 102
  • 142
dexter
  • 31
  • 2
  • 5
  • 1
    Do you have a specific question about this error? Note: You'll find several very similar posts if look at the related panel. – morechilli Mar 05 '12 at 12:33
  • i want to navigate to the home window from the verificationform.but this error occurs.am experiencing this type of error for the first time and i tried a code using thread from another post and it didnt helped....can u pleas help me? – dexter Mar 05 '12 at 12:36
  • Can you describe your use of threads and which threads have been set to [STAThread]? – morechilli Mar 05 '12 at 12:46
  • Don't create windows on a worker thread. Use Dispatcher.BeginInvoke instead. – Hans Passant Mar 05 '12 at 13:41
  • i have tried dispatcher.invoke. i should have have the object of the window to call the dispatcher object and when i create the object //mainwindow mwobj=new mainwindow();// i get the error "The calling thread must be STA, because many UI components require this" in the public mainwindow(){....} in the mainwindow.xaml.cs. how can i solve this? – dexter Mar 11 '12 at 05:53

3 Answers3

4
Dispatcher.BeginInvoke((Action)(() =>
        {
            if (result.Verified)
            {
                MakeReport("The fingerprint was VERIFIED.");
                Home h = new Home();
                this.Hide();
                h.Show();
            }
        })); 
keft
  • 266
  • 1
  • 8
1

WPF Elements must be created on a STA. You are probably facing this issue, because you are trying to create WPF elements from a non STA thread. You can set the thread to STA by setting its apartment model to STA.

Vibes
  • 33
  • 6
0

So the answer from keftmedei above works fine .

Here is a full example trying to launch a process from a MVVMLight RelayCommand

Without using Dispatcher, this ViewFile method went off to Tralfamador to visit the plumber's helper people without leaving a forwarding address e.g. EXCEPTION, Will Robinson!!! (see Vonnegut, see Lost In Space...)

    /// <summary>
    /// Run a file by Process exec - use the shell file association
    /// Run it in its own thread by using the Dispatcher
    /// </summary>
    /// <param name="fileName"></param>
    [STAThread]
    public static void ProcessExecFileByName(string fileName)
    {
        try
        {
            Application.Current.Dispatcher.BeginInvoke((Action)(() =>
            {
                ViewFile(fileName);
            }));
        }
        catch (Exception ex)
        {
            ex.PreserveStackTrace();
            var sb = new StringBuilder();
            sb.AppendLine("File to view: " + fileName);
            ex.AppendErrorData(sb, System.Reflection.MethodBase.GetCurrentMethod().Name);
            throw;
        }
    }


    /// View the file using the Shell file association 
    private static void ViewFile(string fileName)
    {
        using (new Helpers.WaitCursor())
        {

            try
            {
                Logger.DebugFormat("Starting process with file {0}", fileName);
                var proc = new Process();
                proc.EnableRaisingEvents = true;
                proc.Exited += new EventHandler(ProcessExecExitedHandler);

                proc.StartInfo = new ProcessStartInfo()
                {
                    FileName = fileName, //put your path here
                    UseShellExecute = true,
                    WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
                };
                proc.Start();
                Logger.DebugFormat("Process started with file {0}", fileName);
            }
            // this is permissive
            catch (FileNotFoundException fileNFEx)
            {
                ShowError(fileNFEx.Message, true, "WARN");
            }
            catch (InvalidOperationException invOpEx)
            {
                invOpEx.PreserveStackTrace();
                throw;
            }
            catch (IOException IOEx)
            {
                IOEx.PreserveStackTrace();
                throw;
            }
            catch (System.Security.SecurityException securityEx)
            {
                securityEx.PreserveStackTrace();
                throw;
            }

            catch (Exception ex)
            {
                ex.PreserveStackTrace();
                throw;

            }
            finally
            {
                //if (!ok)
                //{
                //    ShowError(statusMessage);
                //}
            }
        }
        return;
    }

    private static void ProcessExecExitedHandler(object sender, System.EventArgs e)
    {

        try
        {
            if (sender == null)
            {
                return;
            }
            if (((Process)sender).HasExited == false)
            {
                ((Process)sender).Kill();
            }

        }
        catch (Exception ex)
        {
            ex.PreserveStackTrace();
            throw;
        }

        Logger.DebugFormat("Process ended with file {0}", ((Process)sender).StartInfo.FileName);
        return;

    }
AllenM
  • 201
  • 2
  • 6