处理一个应用程序,它将监视一些文件和文件更改,显示每个文件的新窗口中的更改。
用户选择要监控的文件后,点击按钮时应打开一个新窗口。在后台,我触发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()
功能中更新文本框的哪个窗口?答案 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");
}