public bool?ShowDialog(Window owner) { NativeMethods.OpenFileName ofn = ToOfn(owner); if (NativeMethods.GetOpenFileName(ofn)) { FromOfn(ofn); return(true); } else { FreeOfn(ofn); return(false); } }
protected void FromOfn(NativeMethods.OpenFileName ofn) { ReadOnlyChecked = (ofn.flags & (int)NativeMethods.OpenFileFlags.OFN_READONLY) != 0; FilterIndex = ofn.filterIndex; if (ofn.fileOffset > 0 && bufferMem[ofn.fileOffset - 1] == '\0') { List <string> result = new List <string>(); int l = 0; for (; l < bufferMem.Length && bufferMem[l] != '\0'; ++l) { } string path = new string(bufferMem, 0, l); while (true) { ++l; int s = l; for (; l < bufferMem.Length && bufferMem[l] != '\0'; ++l) { } if (l < s + 2) { break; } string name = new string(bufferMem, s, l - s); result.Add(System.IO.Path.Combine(path, name)); } FileNames = result.ToArray(); FileName = FileNames[0]; } else { int l = 0; for (; l < bufferMem.Length && bufferMem[l] != '\0'; ++l) { } FileName = new string(bufferMem, 0, l); FileNames = new string[] { FileName }; } FreeOfn(ofn); }
protected NativeMethods.OpenFileName ToOfn(Window owner) { NativeMethods.OpenFileName ofn = new NativeMethods.OpenFileName(); ofn.structSize = Marshal.SizeOf(ofn); ofn.dlgOwner = ((HwndSource)HwndSource.FromVisual(owner)).Handle; if (!string.IsNullOrEmpty(Filter)) { StringBuilder sb = new StringBuilder(); string[] parts = Filter.Split('|'); for (int i = 1; i < parts.Length; i += 2) { sb.Append(parts[i - 1]); sb.Append('\0'); sb.Append(parts[i]); sb.Append('\0'); } sb.Append('\0'); sb.Append('\0'); ofn.filter = sb.ToString(); } ofn.filterIndex = FilterIndex; bufferMem = new char[64001]; memHandle = GCHandle.Alloc(bufferMem, GCHandleType.Pinned); ofn.file = memHandle.AddrOfPinnedObject(); ofn.maxFile = 64000; ofn.title = Title; ofn.flags = (int)NativeMethods.OpenFileFlags.OFN_EXPLORER | (CheckFileExists ? (int)NativeMethods.OpenFileFlags.OFN_FILEMUSTEXIST : 0) | (CheckPathExists ? (int)NativeMethods.OpenFileFlags.OFN_PATHMUSTEXIST : 0) | (DereferenceLinks ? 0 : (int)NativeMethods.OpenFileFlags.OFN_NODEREFERENCELINKS) | (MultiSelect ? (int)NativeMethods.OpenFileFlags.OFN_ALLOWMULTISELECT : 0) | (ReadOnlyChecked ? (int)NativeMethods.OpenFileFlags.OFN_READONLY : 0) | (RestoreDirectory ? (int)NativeMethods.OpenFileFlags.OFN_NOCHANGEDIR : 0) | (ShowReadOnly ? 0 : (int)NativeMethods.OpenFileFlags.OFN_HIDEREADONLY) | (ValidateNames ? 0 : (int)NativeMethods.OpenFileFlags.OFN_NOVALIDATE); ofn.defExt = DefaultExt; return(ofn); }
protected void FreeOfn(NativeMethods.OpenFileName ofn) { memHandle.Free(); bufferMem = null; }