Programmaticaly打开新窗口并定期更新它们

时间:2017-07-12 12:45:35

标签: c# wpf window visual-studio-2017

处理一个应用程序,它将监视一些文件和文件更改,显示每个文件的新窗口中的更改。

用户选择要监控的文件后,点击按钮时应打开一个新窗口。在后台,我触发FileSystemWatcher来观看此文件的更改。一旦发生变化,我必须用一些信息更新这个新打开的窗口(带文本框)。

我已经设置了新的Window1(项目 - >添加窗口 - >窗口(WPF))。 其余代码如下所示:

FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = current_log.FullName.Substring(0, current_log.FullName.LastIndexOf('\\'));

watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;

watcher.Filter = current_log.Name;
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;

//check if window is already active
//????

//open new window
Window1 log_window = new Window1();
log_window.Show();
log_window.txt_log_window_messages.AppendText("ddd\n");

问题:

  • 如何检查此文件是否已启用监视器窗口,以便不再打开它?
  • 如何识别我应该在OnChanged()功能中更新文本框的哪个窗口?

1 个答案:

答案 0 :(得分:0)

我建议在这里使用Dictionary。像这样:

ictionary<string, Window1> files = new Dictionary<string, Window1>();

private void init()
{
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = current_log.FullName.Substring(0, current_log.FullName.LastIndexOf('\\'));

    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
       | NotifyFilters.FileName | NotifyFilters.DirectoryName;

    watcher.Filter = current_log.Name;
    watcher.Changed += Watcher_Changed;
    watcher.EnableRaisingEvents = true;
}

private void Watcher_Changed(object sender, FileSystemEventArgs e)
{
    if(!files.ContainsKey(e.Name))
    {
        //open new window
        Window1 log_window_new = new Window1();            

        files.Add(e.Name, log_window_new);
        log_window_new.Show();
        log_window_new.txt_log_window_messages.AppendText("ddd\n");
    }

    // Update existing window
    Window1 log_window= files[e.Name];
    log_window.txt_log_window_messages.AppendText("tttt\n");
}