关闭OpenFileDialog/SaveFileDialog

Maa*_*anu 4 .net c# winforms

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

如何关闭OpenFileDialog和CloseFileDialog?

Han*_*ant 10

这将需要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 <hWnd> 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);
}
Run Code Online (Sandbox Code Playgroud)