簡體   English   中英

WPF:輸出正確,但窗口未顯示

[英]WPF: The Output is Correct But the Window doesn't show up

我正在開發WPF應用程序。 我需要一種方法,每5秒運行一次,並輸出它捕獲的信息。 我使用DateTime的差值來確定是否經過了5秒。 當我開始運行它時,我可以看到每5秒輸出一次正確的信息。 但是,該應用程序的窗口未顯示,我也無法在狀態欄中找到它的圖標。 這是我的代碼public MainWindow():

InitializeComponent();            
    DateTime now;
        DateTime _lastTime5SecondsHadPassed = DateTime.Now; ;
        TimeSpan elapsed;
        do
        {
            now = DateTime.Now;
            elapsed = now - _lastTime5SecondsHadPassed;
            if (elapsed.Seconds >= 10)
            {
                title = GetActiveWindowTitle();
                Trace.WriteLine(title);
                _lastTime5SecondsHadPassed = DateTime.Now;
            }

        } while (true);

后來我發現將代碼移入的任何窗口都可以正常顯示其他窗口,但是每次當切換到帶有此代碼的窗口時,該窗口都不會顯示。 有人有什么主意嗎? 提前致謝!

克萊門斯絕對是正確的。 當前代碼正在產生一個無限循環,該循環不允許程序的其余部分繼續進行。

以下代碼是從WPF教程中偷偷竊取的。

Xaml for Window:

<Window x:Class="WpfTutorialSamples.Misc.DispatcherTimerSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="DispatcherTimerSample" Height="150" Width="250">
    <Grid>
        <Label Name="lblTime" FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</Window>

以及后面的代碼:

using System;
using System.Windows;
using System.Windows.Threading;

namespace WpfTutorialSamples.Misc
{
        public partial class DispatcherTimerSample : Window
        {
                public DispatcherTimerSample()
                {
                        InitializeComponent();
                        DispatcherTimer timer = new DispatcherTimer();
                        timer.Interval = TimeSpan.FromSeconds(1);
                        timer.Tick += timer_Tick;
                        timer.Start();
                }

                void timer_Tick(object sender, EventArgs e)
                {
                        lblTime.Content = DateTime.Now.ToLongTimeString();
                }
        }
}

您會注意到,Window的構造函數會創建一個1秒鍾的計時器。 每秒,窗口上的標簽將更新為DateTime.Now.ToLongTimeString()的值(例如10:30:15)。

暫無
暫無

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

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