Run program after wpf windows form appears

2020-02-14 23:58发布

Hello i have problem with wpf (c#) project. this is my source

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            MessageBox.Show("Test");
        }
    }
}

i want to run my program

MessageBox.Show("Test");

after windows form appears ... but in this code when i start the program, just first show Test in message box and after that windows form appears ! what should i do to first windows form appears and after that a message box open to show the (Test)? i am using visual studio 2015 (WPF) project

标签: c# wpf xaml
1条回答
▲ chillily
2楼-- · 2020-02-15 01:02

You should write your code in the Window_Load event:

public MainWindow()
{
    InitializeComponent();
    Loaded += MainWindow_Loaded;
}

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Test");
}

EDIT: To work with longer operations like (used a function with more than 10 function inside as you wanted) you could use ThreadPool like this:

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    ThreadPool.QueueUserWorkItem(_ =>
    {
        //Longer Process (//set the operation in another thread so that the UI thread is kept responding)
        Dispatcher.BeginInvoke(new Action(() =>
        {                    
            //use the Dispatcher to "return" to the UI thread
            //To change the UI elements like label you should put them here like : label1.Text = ""; 
        }));
    });
}
查看更多
登录 后发表回答