不使用Microsoft.Win32的Openfiledailog框

时间:2015-09-23 11:18:49

标签: c# wpf winforms mvvm

我使用的是使用ike的openfiledailog框,但我想在不使用Microsoft.Win32参考的情况下执行相同的功能

  Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
  dlg.DefaultExt = ".png";
  dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif";
  //Nullable<bool> result =
  dlg.ShowDialog();

1 个答案:

答案 0 :(得分:2)

选项1

您可以创建自己的对话框,显示文件列表并让用户选择文件。

选项2

您可以改为使用GetOpenFileName

[DllImport("comdlg32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool GetOpenFileName([In, Out] OpenFileName ofn);

这是pinvoke.net page

以下是您需要的工作样本:

[DllImport("comdlg32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern bool GetOpenFileName([In, Out] OpenFileName ofn);

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenFileName
{
    public int structSize = 0;
    public IntPtr dlgOwner = IntPtr.Zero;
    public IntPtr instance = IntPtr.Zero;
    public String filter = null;
    public String customFilter = null;
    public int maxCustFilter = 0;
    public int filterIndex = 0;
    public String file = null;
    public int maxFile = 0;
    public String fileTitle = null;
    public int maxFileTitle = 0;
    public String initialDir = null;
    public String title = null;
    public int flags = 0;
    public short fileOffset = 0;
    public short fileExtension = 0;
    public String defExt = null;
    public IntPtr custData = IntPtr.Zero;
    public IntPtr hook = IntPtr.Zero;
    public String templateName = null;
    public IntPtr reservedPtr = IntPtr.Zero;
    public int reservedInt = 0;
    public int flagsEx = 0;
}

private void OpenButton_Click(object sender, EventArgs e)
{
    OpenFileName openFileName = new OpenFileName();
    openFileName.structSize = Marshal.SizeOf(openFileName);
    openFileName.filter = "JPEG Files (*.jpeg)\0*.jpeg\0PNG Files (*.png)\0*.png\0JPG Files (*.jpg)\0*.jpg\0GIF Files (*.gif)\0*.gif\0";
    openFileName.file = new String(new char[256]);
    openFileName.maxFile = openFileName.file.Length;
    openFileName.fileTitle = new String(new char[64]);
    openFileName.maxFileTitle = openFileName.fileTitle.Length;
    openFileName.title = "Open";
    openFileName.defExt = "png";

    if (GetOpenFileName(openFileName))
    {
        MessageBox.Show(openFileName.file);
    }
}

基于MSDNPInvoke以及Arie代码。