Example #1
0
        private static string BrowseForFileOpen(IntPtr owner, string filter, string initialPath = null, string title = null) {
            IVsUIShell uiShell = VsAppShell.Current.GetGlobalService<IVsUIShell>(typeof(SVsUIShell));
            if (uiShell == null) {
                return null;
            }

            if (owner == IntPtr.Zero) {
                ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner));
            }

            VSOPENFILENAMEW[] openInfo = new VSOPENFILENAMEW[1];
            openInfo[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW));
            openInfo[0].pwzFilter = filter.Replace('|', '\0') + "\0";
            openInfo[0].hwndOwner = owner;
            openInfo[0].pwzDlgTitle = title;
            openInfo[0].nMaxFileName = 260;
            var pFileName = Marshal.AllocCoTaskMem(520);
            openInfo[0].pwzFileName = pFileName;
            openInfo[0].pwzInitialDir = Path.GetDirectoryName(initialPath);
            var nameArray = (Path.GetFileName(initialPath) + "\0").ToCharArray();
            Marshal.Copy(nameArray, 0, pFileName, nameArray.Length);

            try {
                int hr = uiShell.GetOpenFileNameViaDlg(openInfo);
                if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED) {
                    return null;
                }
                ErrorHandler.ThrowOnFailure(hr);
                return Marshal.PtrToStringAuto(openInfo[0].pwzFileName);
            } finally {
                if (pFileName != IntPtr.Zero) {
                    Marshal.FreeCoTaskMem(pFileName);
                }
            }
        }
Example #2
0
        /// <summary>
        /// Displays Visul Studio dialog for selecting files
        /// </summary>
        /// <param name="title">Dialog title</param>
        /// <param name="initialDirectory">Initial directory</param>
        /// <param name="filter">Filter - same as FileDialog filter, but separated with \0</param>
        /// <param name="filterIndex">Selected filter</param>
        /// <param name="flags">Mask of OFN flags</param>
        /// <returns>Selected file paths separated with \0</returns>
        public static string[] SelectFilesViaDlg(string title, string initialDirectory, string filter, uint filterIndex, uint flags)
        {
            uint buffersize = 255;

            VSOPENFILENAMEW o = new VSOPENFILENAMEW();

            o.dwFlags       = flags;
            o.pwzInitialDir = initialDirectory;
            o.pwzFilter     = filter;
            o.pwzDlgTitle   = title;
            o.nFilterIndex  = filterIndex;
            o.nMaxFileName  = buffersize;
            o.lStructSize   = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW));
            o.pwzFileName   = Marshal.StringToBSTR(new string('\0', (int)buffersize));

            IntPtr dialogOwner;
            int    hr = UIShell.GetDialogOwnerHwnd(out dialogOwner);

            Marshal.ThrowExceptionForHR(hr);

            o.hwndOwner = dialogOwner;

            VSOPENFILENAMEW[] arr = new VSOPENFILENAMEW[1] {
                o
            };
            hr = UIShell.GetOpenFileNameViaDlg(arr);
            if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED)
            {
                return(null);
            }
            Marshal.ThrowExceptionForHR(hr);

            string returnedData = Marshal.PtrToStringBSTR(arr[0].pwzFileName);

            string[] tokens = returnedData.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
            if (tokens.Length == 0)
            {
                throw new Exception("Unexpected OpenFileDialog result.");
            }

            if (tokens.Length == 1)
            {
                return(new string[] { tokens[0] });
            }
            else
            {
                string   directory = tokens[0];
                string[] ret       = new string[tokens.Length - 1];

                for (int i = 1; i < tokens.Length; i++)
                {
                    ret[i - 1] = Path.Combine(directory, tokens[i]);
                }

                return(ret);
            }
        }
        public static string[] SelectMultipleFilesUsingDialog(IntPtr handle, string title, string filter, string path,
                                                              bool multiselect, string helpTopic)
        {
            var vsUiShell2 = GetService(typeof(SVsUIShell)) as IVsUIShell2;

            if (vsUiShell2 == null)
            {
                return(null);
            }
            if (filter != null)
            {
                filter = filter.Replace('|', char.MinValue) + char.MinValue;
            }
            var vsopenfilenamew = new VSOPENFILENAMEW();

            string[]  strArray = null;
            var       num1     = IntPtr.Zero;
            const int num2     = 16384;
            const int num3     = 2 * num2;

            try
            {
                num1 = Marshal.AllocCoTaskMem(num3);
                NativeMethods.ZeroMemory(num1, num3);
                vsopenfilenamew.lStructSize   = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW));
                vsopenfilenamew.hwndOwner     = handle;
                vsopenfilenamew.pwzFilter     = filter;
                vsopenfilenamew.pwzDlgTitle   = title;
                vsopenfilenamew.pwzFileName   = num1;
                vsopenfilenamew.nMaxFileName  = num2;
                vsopenfilenamew.pwzInitialDir = path;
                vsopenfilenamew.dwFlags       = 8U;
                if (multiselect)
                {
                    vsopenfilenamew.dwFlags |= 512U;
                }
                var pOpenFileName = new[]
                {
                    vsopenfilenamew
                };
                if (vsUiShell2.GetOpenFileNameViaDlgEx(pOpenFileName, helpTopic) == 0)
                {
                    strArray = GetSelectedFiles(num1, multiselect);
                }
            }
            finally
            {
                if (num1 != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(num1);
                }
            }
            return(strArray);
        }
Example #4
0
        public string BrowseForFileOpen(IntPtr owner, string filter, string initialPath = null, string title = null)
        {
            IVsUIShell uiShell = VsAppShell.Current.GetGlobalService <IVsUIShell>(typeof(SVsUIShell));

            if (uiShell == null)
            {
                return(null);
            }

            if (owner == IntPtr.Zero)
            {
                ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner));
            }

            VSOPENFILENAMEW[] openInfo = new VSOPENFILENAMEW[1];
            openInfo[0].lStructSize  = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW));
            openInfo[0].pwzFilter    = filter.Replace('|', '\0') + "\0";
            openInfo[0].hwndOwner    = owner;
            openInfo[0].pwzDlgTitle  = title;
            openInfo[0].nMaxFileName = 260;
            var pFileName = Marshal.AllocCoTaskMem(520);

            openInfo[0].pwzFileName   = pFileName;
            openInfo[0].pwzInitialDir = Path.GetDirectoryName(initialPath);
            var nameArray = (Path.GetFileName(initialPath) + "\0").ToCharArray();

            Marshal.Copy(nameArray, 0, pFileName, nameArray.Length);

            try {
                int hr = uiShell.GetOpenFileNameViaDlg(openInfo);
                if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED)
                {
                    return(null);
                }
                ErrorHandler.ThrowOnFailure(hr);
                return(Marshal.PtrToStringAuto(openInfo[0].pwzFileName));
            } finally {
                if (pFileName != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pFileName);
                }
            }
        }
Example #5
0
        /// <summary>
        /// Displays the Open File dialog and allows the user to select a file.
        /// </summary>
        /// <param name="filter">Mandatory filter such as "C# Files (*.cs)|*.cs"</param>
        /// <param name="initialPath">Optional initial file path</param>
        /// <param name="title">Optional dialog title</param>
        /// <returns></returns>
        public static string FileOpen(string filter, string initialPath = null, string title = null)
        {
            var uiShell = UiShell;

            if (uiShell == null)
            {
                return(null);
            }

            uiShell.GetDialogOwnerHwnd(out var owner);
            var fs = new VSOPENFILENAMEW[1];

            fs[0].lStructSize  = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW));
            fs[0].pwzFilter    = filter.Replace('|', '\0') + "\0";
            fs[0].hwndOwner    = owner;
            fs[0].pwzDlgTitle  = title;
            fs[0].nMaxFileName = 260;
            var pFileName = Marshal.AllocCoTaskMem(520);

            fs[0].pwzFileName   = pFileName;
            fs[0].pwzInitialDir = initialPath;
            var nameArray = "\0".ToCharArray();

            Marshal.Copy(nameArray, 0, pFileName, nameArray.Length);
            try
            {
                var hr = uiShell.GetOpenFileNameViaDlg(fs);
                if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED)
                {
                    return(null);
                }
                ErrorHandler.ThrowOnFailure(hr);
                return(Marshal.PtrToStringAuto(fs[0].pwzFileName));
            }
            finally
            {
                if (pFileName != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pFileName);
                }
            }
        }
Example #6
0
        public static string BrowseForFileOpen(this IServiceProvider serviceProvider, IntPtr owner, string filter, string initialPath = null)
        {
            if (string.IsNullOrEmpty(initialPath))
            {
                initialPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar;
            }

            IVsUIShell uiShell = serviceProvider.GetService(typeof(SVsUIShell)) as IVsUIShell;

            if (null == uiShell)
            {
                using (var sfd = new System.Windows.Forms.OpenFileDialog()) {
                    sfd.AutoUpgradeEnabled = true;
                    sfd.Filter             = filter;
                    sfd.FileName           = Path.GetFileName(initialPath);
                    sfd.InitialDirectory   = Path.GetDirectoryName(initialPath);
                    DialogResult result;
                    if (owner == IntPtr.Zero)
                    {
                        result = sfd.ShowDialog();
                    }
                    else
                    {
                        result = sfd.ShowDialog(NativeWindow.FromHandle(owner));
                    }
                    if (result == DialogResult.OK)
                    {
                        return(sfd.FileName);
                    }
                    else
                    {
                        return(null);
                    }
                }
            }

            if (owner == IntPtr.Zero)
            {
                ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner));
            }

            VSOPENFILENAMEW[] openInfo = new VSOPENFILENAMEW[1];
            openInfo[0].lStructSize  = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW));
            openInfo[0].pwzFilter    = filter.Replace('|', '\0') + "\0";
            openInfo[0].hwndOwner    = owner;
            openInfo[0].nMaxFileName = 260;
            var pFileName = Marshal.AllocCoTaskMem(520);

            openInfo[0].pwzFileName   = pFileName;
            openInfo[0].pwzInitialDir = Path.GetDirectoryName(initialPath);
            var nameArray = (Path.GetFileName(initialPath) + "\0").ToCharArray();

            Marshal.Copy(nameArray, 0, pFileName, nameArray.Length);
            try {
                int hr = uiShell.GetOpenFileNameViaDlg(openInfo);
                if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED)
                {
                    return(null);
                }
                ErrorHandler.ThrowOnFailure(hr);
                return(Marshal.PtrToStringAuto(openInfo[0].pwzFileName));
            } finally {
                if (pFileName != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(pFileName);
                }
            }
        }
 int IVsUIShell.GetOpenFileNameViaDlg(VSOPENFILENAMEW[] openFileName)
 {
     throw new NotImplementedException();
 }
Example #8
0
		public void GetOpenFileNameViaDlgEx2(VSOPENFILENAMEW[] openFileName, string HelpTopic, string openButtonLabel) {
			throw new NotImplementedException();
		}
        public static string BrowseForFileOpen(
            IntPtr owner,
            string filter,
            string initialPath = null,
            string title = null
        ) {
            if (string.IsNullOrEmpty(initialPath)) {
                initialPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + Path.DirectorySeparatorChar;
            }

            IVsUIShell uiShell = GetService(typeof(SVsUIShell)) as IVsUIShell;
            if (null == uiShell) {
                using (var ofd = new System.Windows.Forms.OpenFileDialog()) {
                    ofd.AutoUpgradeEnabled = true;
                    ofd.Filter = filter;
                    ofd.FileName = Path.GetFileName(initialPath);
                    ofd.InitialDirectory = Path.GetDirectoryName(initialPath);
                    if (!string.IsNullOrEmpty(title)) {
                        ofd.Title = title;
                    }
                    DialogResult result;
                    if (owner == IntPtr.Zero) {
                        result = ofd.ShowDialog();
                    } else {
                        result = ofd.ShowDialog(NativeWindow.FromHandle(owner));
                    }
                    if (result == DialogResult.OK) {
                        return ofd.FileName;
                    } else {
                        return null;
                    }
                }
            }

            if (owner == IntPtr.Zero) {
                ErrorHandler.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out owner));
            }

            VSOPENFILENAMEW[] openInfo = new VSOPENFILENAMEW[1];
            openInfo[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW));
            openInfo[0].pwzFilter = filter.Replace('|', '\0') + "\0";
            openInfo[0].hwndOwner = owner;
            openInfo[0].pwzDlgTitle = title;
            openInfo[0].nMaxFileName = 260;
            var pFileName = Marshal.AllocCoTaskMem(520);
            openInfo[0].pwzFileName = pFileName;
            openInfo[0].pwzInitialDir = Path.GetDirectoryName(initialPath);
            var nameArray = (Path.GetFileName(initialPath) + "\0").ToCharArray();
            Marshal.Copy(nameArray, 0, pFileName, nameArray.Length);
            try {
                int hr = uiShell.GetOpenFileNameViaDlg(openInfo);
                if (hr == VSConstants.OLE_E_PROMPTSAVECANCELLED) {
                    return null;
                }
                ErrorHandler.ThrowOnFailure(hr);
                return Marshal.PtrToStringAuto(openInfo[0].pwzFileName);
            } finally {
                if (pFileName != IntPtr.Zero) {
                    Marshal.FreeCoTaskMem(pFileName);
                }
            }
        }
Example #10
0
        /// <summary>
        /// Shows the Visual Studio open file dialog.
        /// </summary>
        /// <param name="dialogTitle">The title for the dialog box.</param>
        /// <param name="filter">The filter for the dialog.</param>
        /// <param name="initialDirectory">The initial starting directory. Can be null to use the current directory.</param>
        /// <returns>An array of paths to the chosen files or an empty array if the user canceled the dialog.</returns>
        public string[] ShowOpenFileDialog(string dialogTitle, string filter, string initialDirectory)
        {
            ArrayList fileNames  = new ArrayList();
            int       bufferSize = NativeMethods.MAX_PATH;

            // Get the HWND to use for the modal file dialog.
            IntPtr     hwnd;
            IVsUIShell uiShell = this.ServiceProvider.GetVsUIShell(classType, "ShowOpenFileDialog");

            NativeMethods.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out hwnd));

            // Create a native string buffer for the file name.
            IntPtr pwzFileName = Marshal.StringToHGlobalUni(new string('\0', bufferSize));

            try
            {
                // Fill in open file options structure.
                VSOPENFILENAMEW[] openFileOptions = new VSOPENFILENAMEW[1];
                openFileOptions[0].lStructSize   = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW));
                openFileOptions[0].hwndOwner     = hwnd;
                openFileOptions[0].pwzDlgTitle   = dialogTitle;
                openFileOptions[0].pwzFileName   = pwzFileName;
                openFileOptions[0].nMaxFileName  = (uint)bufferSize;
                openFileOptions[0].pwzFilter     = filter;
                openFileOptions[0].pwzInitialDir = initialDirectory;
                openFileOptions[0].dwFlags       = (uint)(VsOpenFileDialogFlags.AllowMultiSelect);

                // Open the Visual Studio open dialog.
                int  hr       = uiShell.GetOpenFileNameViaDlg(openFileOptions);
                bool canceled = (hr == NativeMethods.OLE_E_PROMPTSAVECANCELLED);
                if (NativeMethods.Failed(hr) && !canceled)
                {
                    NativeMethods.ThrowOnFailure(hr);
                }

                // Get the file name(s).
                if (openFileOptions[0].pwzFileName != IntPtr.Zero && !canceled)
                {
                    // We want to get the entire buffered string because if multiple files were selected then it has
                    // the following format: directory\0file1\0file2\0...fileN\0\0. Note that it ends with two null
                    // terminators.
                    string rawDialogPath = Marshal.PtrToStringUni(openFileOptions[0].pwzFileName, bufferSize);

                    // These will hold our currently parsed values.
                    StringBuilder directory        = new StringBuilder();
                    StringBuilder fileName         = new StringBuilder();
                    bool          parsingDirectory = true;

                    // Walk over the raw string to pull out the directory and the file names.
                    for (int i = 0; i < rawDialogPath.Length; i++)
                    {
                        char c     = rawDialogPath[i];
                        char nextC = (i + 1 < rawDialogPath.Length ? rawDialogPath[i + 1] : '\0');

                        // If we've hit a null termination, then we have to stop parsing for a second and add an
                        // item to our array.
                        if (c != '\0')
                        {
                            if (parsingDirectory)
                            {
                                directory.Append(c);
                            }
                            else
                            {
                                fileName.Append(c);
                            }
                        }
                        else
                        {
                            if (parsingDirectory)
                            {
                                parsingDirectory = false;
                            }
                            else
                            {
                                // We've seen another file, so let's add the absolute path to our array.
                                string absolutePath = Path.Combine(directory.ToString(), fileName.ToString());
                                absolutePath = PackageUtility.CanonicalizeFilePath(absolutePath);
                                fileNames.Add(absolutePath);

                                // Clear the file name StringBuilder for the next round.
                                fileName.Length = 0;
                            }

                            // If we are at the double null termination then we can quit parsing.
                            if (nextC == '\0')
                            {
                                // If the user only selected one file, then our parsed directory should be the full file name.
                                if (fileNames.Count == 0)
                                {
                                    fileNames.Add(directory.ToString());
                                }
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
                // Release the string buffer.
                if (pwzFileName != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pwzFileName);
                }
            }

            return((string[])fileNames.ToArray(typeof(string)));
        }
Example #11
0
        /// <summary>
        /// Shows the Visual Studio open file dialog.
        /// </summary>
        /// <param name="dialogTitle">The title for the dialog box.</param>
        /// <param name="filter">The filter for the dialog.</param>
        /// <param name="initialDirectory">The initial starting directory. Can be null to use the current directory.</param>
        /// <returns>An array of paths to the chosen files or an empty array if the user canceled the dialog.</returns>
        public string[] ShowOpenFileDialog(string dialogTitle, string filter, string initialDirectory)
        {
            ArrayList fileNames = new ArrayList();
            int bufferSize = NativeMethods.MAX_PATH;

            // Get the HWND to use for the modal file dialog.
            IntPtr hwnd;
            IVsUIShell uiShell = this.ServiceProvider.GetVsUIShell(classType, "ShowOpenFileDialog");
            NativeMethods.ThrowOnFailure(uiShell.GetDialogOwnerHwnd(out hwnd));

            // Create a native string buffer for the file name.
            IntPtr pwzFileName = Marshal.StringToHGlobalUni(new string('\0', bufferSize));

            try
            {
                // Fill in open file options structure.
                VSOPENFILENAMEW[] openFileOptions = new VSOPENFILENAMEW[1];
                openFileOptions[0].lStructSize = (uint)Marshal.SizeOf(typeof(VSOPENFILENAMEW));
                openFileOptions[0].hwndOwner = hwnd;
                openFileOptions[0].pwzDlgTitle = dialogTitle;
                openFileOptions[0].pwzFileName = pwzFileName;
                openFileOptions[0].nMaxFileName = (uint)bufferSize;
                openFileOptions[0].pwzFilter = filter;
                openFileOptions[0].pwzInitialDir = initialDirectory;
                openFileOptions[0].dwFlags = (uint)(VsOpenFileDialogFlags.AllowMultiSelect);

                // Open the Visual Studio open dialog.
                int hr = uiShell.GetOpenFileNameViaDlg(openFileOptions);
                bool canceled = (hr == NativeMethods.OLE_E_PROMPTSAVECANCELLED);
                if (NativeMethods.Failed(hr) && !canceled)
                {
                    NativeMethods.ThrowOnFailure(hr);
                }

                // Get the file name(s).
                if (openFileOptions[0].pwzFileName != IntPtr.Zero && !canceled)
                {
                    // We want to get the entire buffered string because if multiple files were selected then it has
                    // the following format: directory\0file1\0file2\0...fileN\0\0. Note that it ends with two null
                    // terminators.
                    string rawDialogPath = Marshal.PtrToStringUni(openFileOptions[0].pwzFileName, bufferSize);

                    // These will hold our currently parsed values.
                    StringBuilder directory = new StringBuilder();
                    StringBuilder fileName = new StringBuilder();
                    bool parsingDirectory = true;

                    // Walk over the raw string to pull out the directory and the file names.
                    for (int i = 0; i < rawDialogPath.Length; i++)
                    {
                        char c = rawDialogPath[i];
                        char nextC = (i + 1 < rawDialogPath.Length ? rawDialogPath[i + 1] : '\0');

                        // If we've hit a null termination, then we have to stop parsing for a second and add an
                        // item to our array.
                        if (c != '\0')
                        {
                            if (parsingDirectory)
                            {
                                directory.Append(c);
                            }
                            else
                            {
                                fileName.Append(c);
                            }
                        }
                        else
                        {
                            if (parsingDirectory)
                            {
                                parsingDirectory = false;
                            }
                            else
                            {
                                // We've seen another file, so let's add the absolute path to our array.
                                string absolutePath = Path.Combine(directory.ToString(), fileName.ToString());
                                absolutePath = PackageUtility.CanonicalizeFilePath(absolutePath);
                                fileNames.Add(absolutePath);

                                // Clear the file name StringBuilder for the next round.
                                fileName.Length = 0;
                            }

                            // If we are at the double null termination then we can quit parsing.
                            if (nextC == '\0')
                            {
                                // If the user only selected one file, then our parsed directory should be the full file name.
                                if (fileNames.Count == 0)
                                {
                                    fileNames.Add(directory.ToString());
                                }
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
                // Release the string buffer.
                if (pwzFileName != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pwzFileName);
                }
            }

            return (string[])fileNames.ToArray(typeof(string));
        }
Example #12
0
 public int GetOpenFileNameViaDlg(VSOPENFILENAMEW[] pOpenFileName) {
     throw new NotImplementedException();
 }