簡體   English   中英

從控制台應用程序啟動 WPF window

[英]Launching a WPF window from a Console application

我正在嘗試使用 WPF window 作為消息彈出窗口,一旦執行任務就會關閉。 我看到的所有文檔都說這不能用 messageBox 完成,這就是我要使用 WPF 的原因。 我發現一個代碼片段允許我打開 WPF window 但它不會將應用程序推進到下一個過程。 下面是我發現的最后一個代碼示例,我認為它顯示了 promise 但 window 沒有打開 -

        [STAThread]
        static void Main(string[] args)
        {
            try
            {
                string filePath = "my new directory";
                var popup = new PopupTest();

                popup.Dispatcher.BeginInvoke
                    (System.Windows.Threading.DispatcherPriority.Normal,
                    (Action)(() =>
                    {
                        popup.Show();
                        
                    }));

                // Do some console application stuff

                do
                {
                    Directory.CreateDirectory(filePath);
                } while (!Directory.Exists(filePath));

                popup.Close();            
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
    } 

cs.xaml 文件只是默認的

    /// Interaction logic for PopupTest.xaml
    /// </summary>
    public partial class PopupTest : Window
    {
        public PopupTest()
        {
            InitializeComponent();
        }
    }

我覺得這應該比我做的更簡單。 任何可以為我指明正確方向的事情都值得贊賞。

您需要參考 WPF 程序集並在 STA 線程上創建並運行System.Windows.Application

[STAThread]
static void Main(string[] args)
{
    var app = new System.Windows.Application();
    app.Run(new PopupTest());
}

Run方法會阻塞並且在應用程序關閉之前不會返回。

如果您想在應用程序運行時做一些事情,您需要在另一個線程上執行此操作:

    [STAThread]
    static async Task Main(string[] args)
    {

        Task t = Task.Run(() => 
        {
            string filePath = "my new directory";
            do
            {
                Directory.CreateDirectory(filePath);
            } while (!Directory.Exists(filePath));
        });

        var app = new System.Windows.Application();
        app.Run(new MainWindow());

        await t;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM