Launching a WPF Window in a Separate Thread

前端 未结 3 1897
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-21 08:03

I\'m using the following code for to open a window in a separate thread

public partial class App : Application
{
    protected override void OnStartup(Startu         


        
相关标签:
3条回答
  • 2020-12-21 08:16

    why you trying to do this? there is (nearly)no reason to run a 2end UI thread inside you application ... if you want a non Modal new Window, instantiate you window and call show.

    Why nearly? Because this is a very complex topic and unless you have a huge budged to develop exactly this behavior, you can live without it.

    0 讨论(0)
  • 2020-12-21 08:22

    @d.moncada, @JPVenson, @TomTom sorry for everyone, espetially to @d.moncada, your answer made me realize my true error, indeed if run once until my code works. But my really problem is that i try to push button1_Click in two ocation, really i take a timer that called a method with the line of the

     private void button1_Click(object sender, RoutedEventArgs e)
    

    Now the solution of my problem is Detecting a Thread is already running in C# .net?

    0 讨论(0)
  • 2020-12-21 08:26

    I believe the problem is that you are setting the ApartmentState after the Thread as started running.

    Try:

    public partial class App : Application
    {
        #region Instance Variables
        private Thread newWindowThread;
    
        #endregion
    
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            newWindowThread = new Thread(new Thread(() =>
            {
                // Create and show the Window
                Config tempWindow = new Config();
                tempWindow.Show();
                // Start the Dispatcher Processing
                System.Windows.Threading.Dispatcher.Run();
            }));
            // Set the apartment state
            newWindowThread.SetApartmentState(ApartmentState.STA);
            // Make the thread a background thread
            newWindowThread.IsBackground = true;
        }
    
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            // Start the thread
            newWindowThread.Start();
        }
    }
    
    0 讨论(0)
提交回复
热议问题