以编程方式打开新窗口并定期更新它们



处理应用程序,这将监视某些文件并在文件更改时,在每个文件的新窗口中显示该更改。

用户选择要监视的文件后,单击按钮时应打开一个新窗口。在后台,我触发FileSystemWatcher监视此文件的更改。一旦发生更改,我必须使用一些信息更新这个新打开的窗口(带有文本框(。

我已经设置了新的窗口1(项目->添加窗口->窗口(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("dddn");

问题:

  • 如何检查此文件是否已经激活了监视器窗口,不再打开它?
  • 如何确定我应该在哪个窗口中更新OnChanged()函数中的文本框?

我建议在这里使用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("dddn");
}
// Update existing window
Window1 log_window= files[e.Name];
log_window.txt_log_window_messages.AppendText("ttttn");
}

最新更新