【问题标题】:Programmaticaly opening new windows and updating them periodically以编程方式打开新窗口并定期更新它们
【发布时间】:2017-07-12 20:58:07
【问题描述】:

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

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

我已经设置了新的 Window1 (Project -> Add Window -> Window (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()函数中我应该在哪个窗口更新文本框?

【问题讨论】:

  • 你可以有一本字典
  • 使用Hashtable\Dictionary,FileName为Key,Window实例为Value。
  • 我喜欢简单的解决方案,谢谢你们!
  • 就像 BugFinder 写的那样,您可以维护一个 Dictionary ,您可以在其中简单地检查用户是否打开了文件(即 Dictionary .ContainsKey 对于文件路径是否为真)。这将同时为您提供对要更新的窗口的引用。

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


【解决方案1】:

我建议在这里与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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 2020-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多