关闭OpenFileDialog / SaveFileDialog

我们要求关闭子表单作为自动注销的一部分。 我们可以通过从计时器线程迭代Application.OpenForms来关闭子表单。 我们无法使用Application.OpenForms关闭OpenFileDialog / SaveFileDialog,因为未列出OpenFileDialog。

如何关闭OpenFileDialog和CloseFileDialog?

这将需要pinvoke,对话框不是表单,而是本机Windows对话框。 基本方法是枚举所有顶层窗口并检查它们的类名是否为“#32770”,即Windows拥有的所有对话框的类名。 并通过发送WM_CLOSE消息强制关闭对话框。

在项目中添加一个新类并粘贴下面显示的代码。 当注销计时器到期时,调用DialogCloser.Execute()。 然后关闭表格。 该代码适用于MessageBox,OpenFormDialog,FolderBrowserDialog,PrintDialog,ColorDialog,FontDialog,PageSetupDialog和SaveFileDialog。

using System; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; static class DialogCloser { public static void Execute() { // Enumerate windows to find dialogs EnumThreadWndProc callback = new EnumThreadWndProc(checkWindow); EnumThreadWindows(GetCurrentThreadId(), callback, IntPtr.Zero); GC.KeepAlive(callback); } private static bool checkWindow(IntPtr hWnd, IntPtr lp) { // Checks if  is a Windows dialog StringBuilder sb = new StringBuilder(260); GetClassName(hWnd, sb, sb.Capacity); if (sb.ToString() == "#32770") { // Close it by sending WM_CLOSE to the window SendMessage(hWnd, 0x0010, IntPtr.Zero, IntPtr.Zero); } return true; } // P/Invoke declarations private delegate bool EnumThreadWndProc(IntPtr hWnd, IntPtr lp); [DllImport("user32.dll")] private static extern bool EnumThreadWindows(int tid, EnumThreadWndProc callback, IntPtr lp); [DllImport("kernel32.dll")] private static extern int GetCurrentThreadId(); [DllImport("user32.dll")] private static extern int GetClassName(IntPtr hWnd, StringBuilder buffer, int buflen); [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp); } 

我不会在一个post中关闭所有子表单,而是提出每个子表单都可以/必须订阅的事件。 提高你的表格可以决定现在该做什么。 清理一些东西,持久化状态,在表单范围内向服务器发送消息,您可以访问openfiledialog并尝试关闭它。

[解决方法]这里是示例:

您应该定义完全透明的窗口ex。 “TRANSP”;

每次需要显示对话框时,都需要显示TRANSP并将TRANSP作为参数传递给ShowDialog方法。

当应用程序关闭时 – 调用Close()窗口的方法。 子对话框将关闭。

  public partial class MainWindow : Window { OpenFileDialog dlg; TranspWnd transpWnd; public MainWindow() { InitializeComponent(); Timer t = new Timer(); t.Interval = 2500; t.Elapsed += new ElapsedEventHandler(t_Elapsed); t.Start(); } void t_Elapsed(object sender, ElapsedEventArgs e) { Dispatcher.BeginInvoke(new Action(() => { transpWnd.Close(); }), null); } private void button1_Click(object sender, RoutedEventArgs e) { transpWnd = new TranspWnd(); transpWnd.Visibility = System.Windows.Visibility.Hidden; //doesn't works right transpWnd.Show(); dlg = new OpenFileDialog(); dlg.ShowDialog(transpWnd); } }