Esempio n. 1
0
        /// <summary>
        /// Get Shell file or folder info with extra flags.
        /// </summary>
        private static ShellObject GetInfo(Shell32.FileInfoItemType identifier, string name, Shell32.FileInfoFlag extraFlags)
        {
            // Create a filesystemobject to hold the result
            ShellObject result = new ShellObject();

            // Create a structure to hold the information
            Shell32.SHFILEINFO info = new Shell32.SHFILEINFO();
            int infoSize = Marshal.SizeOf(typeof(Shell32.SHFILEINFO));

            // Build the flags
            Shell32.FileInfoFlag flags = Shell32.FileInfoFlag.Icon | Shell32.FileInfoFlag.UseFileAttributes;
            flags |= extraFlags;

            // Retrieve the small icon
            Shell32.SHGetFileInfo(name, identifier, ref info, infoSize, flags | Shell32.FileInfoFlag.IconSizeSmall);
            result.SmallIcon = Icon.FromHandle(info.hIcon).ToBitmap();
            User32.DestroyIcon(info.hIcon);

            // Retrieve the large icon and type info
            Shell32.SHGetFileInfo(name, identifier, ref info, infoSize, flags | Shell32.FileInfoFlag.IconSizeLarge | Shell32.FileInfoFlag.TypeName);
            result.LargeIcon = Icon.FromHandle(info.hIcon).ToBitmap();
            result.TypeName = info.szTypeName;
            User32.DestroyIcon(info.hIcon);

            return result;
        }
Esempio n. 2
0
        private static Boolean checkStatus(int ItemCount, Shell32.Folder DestFlder)
        {
            DateTime timeoutDeadline = DateTime.Now.AddMinutes(1);

            for (; ; )
            {
                //Are we past the deadline?
                if (DateTime.Now > timeoutDeadline)
                {
                    break;
                }

                //Check the number of items in the new zip to see if it matches
                //the number of items in the original source location

                //Only check the item count every .25 seconds
                System.Threading.Thread.Sleep(250);

                int ZipFileItemCount = RecurseCount(DestFlder.Items());

                if (ItemCount == ZipFileItemCount)
                {
                    break;
                }
            }
            return true;
        }
            public void Perform(Shell32InstanceWrapper shell, string destDir, Shell32.FolderItem src, TimeSpan timeout, CopyReaderDelegate reader)
            {
                var destFile = Path.GetFullPath(Path.Combine(destDir, Path.GetFileName(src.Path)));

                var destFolder = shell.NameSpace(destDir);
                StartCopy(src, destFolder);
                FinishCopy(destFile, timeout, reader);
            }
        private static string GetArtist(Shell32.Folder shellFolder, Shell32.FolderItem shellFile)
        {
            if (!string.IsNullOrEmpty(shellFolder.GetDetailsOf(shellFile, AUTHOR)))
                return shellFolder.GetDetailsOf(shellFile, AUTHOR);

            if (!string.IsNullOrEmpty(shellFolder.GetDetailsOf(shellFile, ALBUM_ARTIST)))
                return shellFolder.GetDetailsOf(shellFile, ALBUM_ARTIST);

            return "Unknown Artist";
        }
Esempio n. 5
0
 public LinkType(Shell32.ShellLinkObject _Link,FileInfo _FileInfo)
 {
     Link = _Link;
     FileInfo = _FileInfo;
     Arguments = Link.Arguments;
     WorkingDirectory = Link.WorkingDirectory;
     Description = Link.Description;
     Target = Link.Target.Path;
     LinkFullName = FileInfo.FullName;
     //Path = Link.Path;
 }
Esempio n. 6
0
        /// <summary>
        /// Initialises the ShellItem, from its PIDL and parent.
        /// </summary>
        /// <param name="pidl">The pidl.</param>
        /// <param name="parentFolder">The parent folder.</param>
        private void Initialise(IntPtr pidl, ShellItem parentFolder)
        {
            //  Set the parent item and relative pidl.
            ParentItem   = parentFolder;
            RelativePIDL = pidl;

            //  Create the fully qualified PIDL.
            PIDL = Shell32.ILCombine(parentFolder.PIDL, pidl);

            //  Use the desktop folder to get attributes.
            var flags = SFGAO.SFGAO_FOLDER | SFGAO.SFGAO_HASSUBFOLDER | SFGAO.SFGAO_BROWSABLE | SFGAO.SFGAO_FILESYSTEM;
            //todo was this parentFolder.ShellFolderInterface.GetAttributesOf(1, ref pidl, ref flags);

            var apidl = Marshal.AllocCoTaskMem(IntPtr.Size * 1);

            Marshal.Copy(new IntPtr[] { pidl }, 0, apidl, 1);

            parentFolder.ShellFolderInterface.GetAttributesOf(1, apidl, ref flags);

            IsFolder      = (flags & SFGAO.SFGAO_FOLDER) != 0;
            HasSubFolders = (flags & SFGAO.SFGAO_HASSUBFOLDER) != 0;

            //  Get the file info.
            var fileInfo = new SHFILEINFO();

            Shell32.SHGetFileInfo(PIDL, 0, out fileInfo, (uint)Marshal.SizeOf(fileInfo),
                                  SHGFI.SHGFI_SMALLICON | SHGFI.SHGFI_SYSICONINDEX | SHGFI.SHGFI_PIDL | SHGFI.SHGFI_DISPLAYNAME | SHGFI.SHGFI_ATTRIBUTES);

            //  Set extended attributes.
            DisplayName = fileInfo.szDisplayName;
            Attributes  = (SFGAO)fileInfo.dwAttributes;
            TypeName    = fileInfo.szTypeName;
            IconIndex   = fileInfo.iIcon;

            //  Are we a folder?
            if (IsFolder)
            {
                //  Bind the shell folder interface.
                IShellFolder shellFolderInterface;
                IntPtr       ppv    = IntPtr.Zero;
                var          result = parentFolder.ShellFolderInterface.BindToObject(pidl, IntPtr.Zero, ref Shell32.IID_IShellFolder,
                                                                                     out ppv);//out shellFolderInterface);
                shellFolderInterface = ((IShellFolder)Marshal.GetObjectForIUnknown(ppv));
                ShellFolderInterface = shellFolderInterface;

                //  Validate the result.
                if (result != 0)
                {
                    //  Throw the failure as an exception.
                    Marshal.ThrowExceptionForHR((int)result);
                }
            }
        }
        private string kind(string extension)
        {
            Shell32.SHFILEINFO shinfo   = new Shell32.SHFILEINFO();
            IntPtr             hSuccess = Shell32.SHGetFileInfo(extension, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo),
                                                                Shell32.SHGFI_TYPENAME | Shell32.SHGFI_USEFILEATTRIBUTES);

            if (hSuccess != IntPtr.Zero)
            {
                return(Convert.ToString(shinfo.szTypeName.Trim()));
            }
            return(null);
        }
Esempio n. 8
0
        public static Icon GetResourceIcon(string resourceReference)
        {
            var    parts = GetResourceRefParts(resourceReference);
            IntPtr hIcon = IntPtr.Zero, hSmIcon = IntPtr.Zero;

            Shell32.SHDefExtractIcon(parts.Item1, parts.Item2, 0, ref hIcon, ref hSmIcon, 0);
            DestroyIcon(hSmIcon);
            var ico = (Icon)Icon.FromHandle(hIcon).Clone();

            DestroyIcon(hIcon);
            return(ico);
        }
Esempio n. 9
0
        public void SHGetKnownFolderPathTest()
        {
            string path;

            //ダウンロードフォルダ
            //Guid id = new Guid("374DE290-123F-4565-9164-39C4925E467B");
            //ライブラリ
            Guid id     = new Guid("031E4825-7B94-4DC3-B131-E946B44C8DD5");
            int  result = Shell32.SHGetKnownFolderPath(id, 0, IntPtr.Zero, out path);

            Debug.Print(path);
        }
Esempio n. 10
0
        protected CsShellDirectory PopulateDictionaries()
        {
            Debug.Print("Populating Dictionaries");
            ActiveShellDirectory = new CsShellDirectory().Create();
            try
            {
                Debug.Print("> Enumerating Files");
                foreach (string ss in Directory.GetFiles(currentPath))
                {
                    FileInfo f = new FileInfo(ss);
                    using (CsShellFile sh = new CsShellFile(ss, SHGFI.SMALLICON | SHGFI.ICON | SHGFI.TYPENAME))
                    {
                        if (!ActiveShellDirectory.Files.Paths.ContainsKey(f.FullName))
                        {
                            ActiveShellDirectory.Files.Paths.Add(f.FullName, sh.GetListItem());
                        }
                        if (!ActiveShellDirectory.Files.IcoPtr.ContainsKey(ss))
                        {
                            ActiveShellDirectory.Files.IcoPtr.Add(f.FullName, sh.IIcon);
                        }
                    }
                }

                Debug.Print("> File Count: {0}", ActiveShellDirectory.Files.Paths.Count);
                Debug.Print("> Enumerating Directories");
                foreach (string ss in Directory.GetDirectories(currentPath))
                {
                    DirectoryInfo        d  = new DirectoryInfo(ss);
                    CsShellFile_ListItem sx = new CsShellFile_ListItem();
                    sx.Path = ss;
                    sx.Name = Path.GetFileName(ss);
                    SHFileInfo sh = Shell32.StrIco(ss, SHGFI.SMALLICON | SHGFI.ICON | SHGFI.TYPENAME);
                    sx.TypeName = sh.szTypeName;
                    if (!ActiveShellDirectory.Directories.Paths.ContainsKey(d.Name))
                    {
                        ActiveShellDirectory.Directories.Paths.Add(d.Name, sx);
                    }
                    if (!ActiveShellDirectory.Directories.IcoPtr.ContainsKey(ss))
                    {
                        ActiveShellDirectory.Directories.IcoPtr.Add(ss, sh.hIcon);
                    }
                    User32.DestroyIcon(sh.hIcon);
                }
                Debug.Print("> Directory Count: {0}", ActiveShellDirectory.Directories.Paths.Count);
            }
            catch (IOException e) {
                MessageBox.Show(e.Message, e.Source);
            }
            catch (Exception e) {
                Debug.Print("{0}", e);
            }
            return(ActiveShellDirectory);
        }
Esempio n. 11
0
        public void Initialize(IntPtr lvHandle, string path, int index)
        {
            var shellItem = Shell32.SHCreateItemFromParsingName(path, IntPtr.Zero, typeof(IShellItem).GUID);

            this.ParentPIDL = IntPtr.Zero;
            this.EnumPIDL   = Shell32.SHGetIDListFromObject(shellItem);
            Marshal.ReleaseComObject(shellItem);
            //this.ParentHandle = lvHandle;

            this.OverlayIconIndex  = -1;
            this.ShieldedIconIndex = -1;
        }
Esempio n. 12
0
 private static IShellItem CreateItemFromIDList(IntPtr pidl)
 {
     //TODO: Consider moving the Try Finally to here
     if (RunningVista)
     {
         return(Shell32.SHCreateItemFromIDList(pidl, typeof(IShellItem).GUID));
     }
     else
     {
         return(new Interop.VistaBridge.ShellItemImpl(pidl, false));
     }
 }
Esempio n. 13
0
        public static IdList GetDesktop()
        {
            IntPtr pidl;

            Shell32.SHGetKnownFolderIDList(FOLDERID_Desktop, // KnownFolders.FOLDERID_Desktop,
                                           KNOWN_FOLDER_FLAG.KF_NO_FLAGS, IntPtr.Zero,
                                           out pidl);
            var idlist = IdList.Create(Decode(pidl));

            Shell32.ILFree(pidl);
            return(idlist);
        }
Esempio n. 14
0
 private void cmnuProperties_Click(object sender, EventArgs e)
 {
     try
     {
         ApplicationJob job = olvJobs.SelectedObject as ApplicationJob;
         Shell32.ShowFileProperties(job.CurrentLocation);
     }
     catch (Exception)
     {
         // ignore if fails for whatever reason
     }
 }
Esempio n. 15
0
        public static IShellFolder GetFolderImpl(this IntPtr pidl,
                                                 ref PidlFolderData data, SBSP wFlags)
        {
            IShellFolder result = null;

            int    hr                  = 0;
            IntPtr pidlTmp             = IntPtr.Zero;
            var    folderTmp           = data.folderTmp;
            var    currentAbsolutePidl = data.currentAbsolutePidl;
            var    folderTmpPtr        = data.folderTmpPtr;
            var    currentFolder       = data.currentFolder;

            IShellFolder desktopFolder     = PidlFolderData.DesktopFolder;
            var          desktopFolderPidl = PidlFolderData.DesktopFolderPidl;

            //  Check to see if we have a desktop pidl, relative pidl or absolite pidl.
            if (Shell32.ILIsEqual(pidl, desktopFolderPidl))
            {
                //  The provided PIDL is the desktop folder.
                pidlTmp   = Shell32.ILClone(desktopFolderPidl);
                folderTmp = desktopFolder;
            }
            else if ((wFlags & SBSP.SBSP_RELATIVE) != 0)
            {
                // SBSP_RELATIVE - pidl is relative from the current folder
                if ((hr = currentFolder.BindToObject(pidl, IntPtr.Zero,
                                                     ref Shell32.IID_IShellFolder,
                                                     out folderTmpPtr)) != WinError.S_OK)
                {
                    return(result); // hr;
                }
                pidlTmp = Shell32.ILCombine(currentAbsolutePidl, pidl);

                folderTmp = (IShellFolder)Marshal.GetObjectForIUnknown(folderTmpPtr);
            }
            else
            {
                // SBSP_ABSOLUTE - pidl is an absolute pidl (relative from desktop)
                PidlClone pidlClone = PidlClone.Of(pidl);
                folderTmp = GetPidlCloneFolder(pidlClone);

                pidlTmp = pidlClone.Handle;
            }

            if (folderTmp == null)
            {
                Shell32.ILFree(pidlTmp);
                return(result); // WinError.E_FAIL;
            }

            result = folderTmp;
            return(result);
        }
Esempio n. 16
0
    // 48X48
    private static IntPtr GetXLIcon(int iImage)
    {
        IImageList spiml = null;
        Guid       guil  = new Guid(IID_IImageList);//or IID_IImageList

        Shell32.SHGetImageList(Shell32.SHIL_EXTRALARGE, ref guil, ref spiml);
        IntPtr hIcon = IntPtr.Zero;

        spiml.GetIcon(iImage, Shell32.ILD_TRANSPARENT | Shell32.ILD_IMAGE, ref hIcon); //

        return(hIcon);
    }
Esempio n. 17
0
 public void Navigate(ShellItem destination)
 {
     this.cache.Clear();
     this.refreshedImages.Clear();
     GC.Collect();
     this.Cancel = true;
     Shell32.SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, -1, -1);
     this.Items = destination.OrderByDescending(o => o.IsFolder).ToArray();
     User32.SendMessage(this.LVHandle, MSG.LVM_SETITEMCOUNT, this.Items.Length, 0);
     this.m_CurrentFolder = destination;
     this.OnNavigated(new NavigatedEventArgs(destination));
 }
Esempio n. 18
0
        public void CanGetDesktopFolderLocationAndPath()
        {
            //  Asserts we can get the desktop folder pidl, get a path for it and free the pidl.
            IntPtr pidl;

            Shell32.SHGetFolderLocation(IntPtr.Zero, CSIDL.CSIDL_DESKTOP, IntPtr.Zero, 0, out pidl);
            var sb = new StringBuilder(260);

            Assert.IsTrue(Shell32.SHGetPathFromIDList(pidl, sb));
            Assert.IsNotNullOrEmpty(sb.ToString());
            Assert.DoesNotThrow(() => Shell32.ILFree(pidl));
        }
Esempio n. 19
0
        static IntPtr GetJumboIcon(int iImage)
        {
            IImageList spiml = null;
            Guid       guil  = new Guid(IID_IImageList2);

            Shell32.SHGetImageList(Shell32.SHIL_JUMBO, ref guil, ref spiml);
            IntPtr hIcon = IntPtr.Zero;

            spiml.GetIcon(iImage, Shell32.ILD_TRANSPARENT | Shell32.ILD_IMAGE, ref hIcon);

            return(hIcon);
        }
Esempio n. 20
0
        public HResult GetParent(out IShellItem ppsi)
        {
            var pidl = Shell32.ILClone(Pidl);

            if (Shell32.ILRemoveLastID(pidl))
            {
                ppsi = new ShellItemImpl(pidl, true);
                return(HResult.S_OK);
            }
            ppsi = null;
            return(HResult.MK_E_NOOBJECT);
        }
Esempio n. 21
0
        //private void OnFileSystemWatcherChanged(object sender, FileSystemEventArgs e)
        //{
        //    Dispatcher.Current.Invoke(() =>
        //    {
        //        try
        //        {
        //            Image image = CreateImageFromFile(e.FullPath);
        //            LoadCircuitBoard(image);
        //        }
        //        catch (Exception exception)
        //        {
        //            Debug.WriteLine(exception);
        //        }
        //    });
        //}

        protected override void OnCreate(ref CreateWindowPacket packet)
        {
            base.OnCreate(ref packet);

            Shell32.DragAcceptFiles(Handle, true);

            textBrush  = new SolidColorBrush(Dx.D2D.Context, textColor);
            textFormat = new TextFormat(Dx.TextFactory, "Consolas", 16);

            LoadDefaultCircuitBoard();
            performanceMonitor.Start();
        }
Esempio n. 22
0
    public static bool ShowFileProperties(string filename)
    {
        var info = new ShellExecuteInfo();

        info.cbSize = Marshal.SizeOf(info);
        info.lpVerb = "properties";
        info.lpFile = filename;
        //info.lpParameters = "Security";
        info.nShow = (int)ShowWindowCommands.Show;
        info.fMask = (uint)ShellExecuteMasks.InvokeIdList;
        return(Shell32.ShellExecuteEx(ref info));
    }
Esempio n. 23
0
        private static async Task parseRecycleBinAction(AppServiceRequestReceivedEventArgs args, string action)
        {
            switch (action)
            {
            case "Empty":
                // Shell function to empty recyclebin
                Shell32.SHEmptyRecycleBin(IntPtr.Zero, null, Shell32.SHERB.SHERB_NOCONFIRMATION | Shell32.SHERB.SHERB_NOPROGRESSUI);
                break;

            case "Query":
                var responseQuery = new ValueSet();
                Shell32.SHQUERYRBINFO queryBinInfo = new Shell32.SHQUERYRBINFO();
                queryBinInfo.cbSize = (uint)Marshal.SizeOf(queryBinInfo);
                var res = Shell32.SHQueryRecycleBin("", ref queryBinInfo);
                if (res == HRESULT.S_OK)
                {
                    var numItems = queryBinInfo.i64NumItems;
                    var binSize  = queryBinInfo.i64Size;
                    responseQuery.Add("NumItems", numItems);
                    responseQuery.Add("BinSize", binSize);
                    await args.Request.SendResponseAsync(responseQuery);
                }
                break;

            case "Enumerate":
                // Enumerate recyclebin contents and send response to UWP
                var responseEnum       = new ValueSet();
                var folderContentsList = new List <ShellFileItem>();
                foreach (var folderItem in recycler)
                {
                    try
                    {
                        var shellFileItem = GetRecycleBinItem(folderItem);
                        folderContentsList.Add(shellFileItem);
                    }
                    catch (FileNotFoundException)
                    {
                        // Happens if files are being deleted
                    }
                    finally
                    {
                        folderItem.Dispose();
                    }
                }
                responseEnum.Add("Enumerate", JsonConvert.SerializeObject(folderContentsList));
                await args.Request.SendResponseAsync(responseEnum);

                break;

            default:
                break;
            }
        }
Esempio n. 24
0
        public void CanFullRoundTripPidl()
        {
            IntPtr pidl;

            Shell32.SHGetKnownFolderIDList(KnownFolders.FOLDERID_Downloads, KNOWN_FOLDER_FLAG.KF_NO_FLAGS, IntPtr.Zero,
                                           out pidl);
            var idList  = PidlManager.PidlToIdlist(pidl);
            var pidl2   = PidlManager.IdListToPidl(idList);
            var idList2 = PidlManager.PidlToIdlist(pidl2);

            Assert.IsTrue(idList.Matches(idList2));
        }
Esempio n. 25
0
        /// <summary>
        /// Function to purge old workspace directories if they were left over (e.g. debug break, crash, etc...)
        /// </summary>
        /// <param name="prevDirectory">The previously used directory path for the project.</param>
        /// <param name="recycle"><b>true</b> to recycle the directory, or <b>false</b> to permenantly delete it.</param>
        /// <exception cref="ArgumentNullException">Thrown when the <paramref name="prevDirectory"/> parameter is <b>null</b>.</exception>
        private void PurgeStaleDirectories(DirectoryInfo prevDirectory, bool recycle)
        {
            int count = 0;

            if (!prevDirectory.Exists)
            {
                return;
            }

            var deleteDir = new DirectoryInfo(prevDirectory.FullName);

            // To avoid issues with delete being an asynchronous operation, we will first rename the directory, and then delete it.
            // This way we can recreate the directory structure without interference (one would hope at least).
            if (!recycle)
            {
                deleteDir.MoveTo(Path.Combine(deleteDir.Parent.FullName, Guid.NewGuid().ToString("N")));
            }

            // Attempt to delete multiple times if the directory is locked (explorer is a jerk sometimes).
            while (count < 4)
            {
                try
                {
                    if (!deleteDir.Exists)
                    {
                        return;
                    }

                    if (recycle)
                    {
                        Program.Log.Print($"Moving '{deleteDir.FullName}' to the recycle bin...", LoggingLevel.Intermediate);
                        Shell32.SendToRecycleBin(deleteDir.FullName, Shell32.FileOperationFlags.FOF_SILENT | Shell32.FileOperationFlags.FOF_NOCONFIRMATION | Shell32.FileOperationFlags.FOF_WANTNUKEWARNING);
                    }
                    else
                    {
                        Program.Log.Print($"Deleting '{deleteDir.FullName}'...", LoggingLevel.Intermediate);
                        deleteDir.Delete(true);
                    }
                    break;
                }
                catch (Exception ex)
                {
                    Program.Log.LogException(ex);
                    ++count;

                    // Give the system some time. Sometimes explorer will release its lock.
                    Thread.Sleep(250);
                }
            }

            prevDirectory.Refresh();
        }
Esempio n. 26
0
        public static List <AssociationPackage> GetAllAssociation(string Path)
        {
            List <AssociationPackage> Association = new List <AssociationPackage>(100);

            try
            {
                string Extension = System.IO.Path.GetExtension(Path).ToLower();

                if (Shell32.SHAssocEnumHandlers(Extension, Shell32.ASSOC_FILTER.ASSOC_FILTER_NONE, out Shell32.IEnumAssocHandlers AssocHandlers) == HRESULT.S_OK)
                {
                    Shell32.IAssocHandler[] Handlers = new Shell32.IAssocHandler[100];

                    if (AssocHandlers.Next(100, Handlers, out uint FetchedNum) == HRESULT.S_OK)
                    {
                        Array.Resize(ref Handlers, Convert.ToInt32(FetchedNum));

                        foreach (Shell32.IAssocHandler Handler in Handlers)
                        {
                            try
                            {
                                if (Handler.GetName(out string FullPath) == HRESULT.S_OK && Handler.GetUIName(out string DisplayName) == HRESULT.S_OK)
                                {
                                    //For UWP application, DisplayName == FullPath
                                    if (DisplayName != FullPath)
                                    {
                                        Association.Add(new AssociationPackage(Extension, FullPath, Handler.IsRecommended() == HRESULT.S_OK));
                                    }
                                }
                            }
                            catch
                            {
                                continue;
                            }
                            finally
                            {
                                Marshal.ReleaseComObject(Handler);
                            }
                        }
                    }
                }

                return(Association);
            }
            catch
            {
                return(Association);
            }
            finally
            {
                Association.TrimExcess();
            }
        }
Esempio n. 27
0
        private DialogBoxResult ShowVistaDialog(IWin32Window owner)
        {
            // ReSharper disable once SuspiciousTypeConversion.Global
            var frm = (IFileDialog) new FileOpenDialogRCW();

            frm.GetOptions(out var options);
            options |= FileOpenDialogOptions.PickFolders |
                       FileOpenDialogOptions.ForceFileSystem |
                       FileOpenDialogOptions.NoValidate |
                       FileOpenDialogOptions.NoTestFileCreate |
                       FileOpenDialogOptions.DontAddToRecent;
            frm.SetOptions(options);
            if (InitialFolder != null)
            {
                var riid = typeof(IShellItem).GUID;
                if (Shell32.SHCreateItemFromParsingName(InitialFolder, IntPtr.Zero, ref riid, out var directoryShellItem) == ErrorCode.S_OK)
                {
                    frm.SetFolder(directoryShellItem);
                }
            }

            if (DefaultFolder != null)
            {
                var riid = typeof(IShellItem).GUID;
                if (Shell32.SHCreateItemFromParsingName(DefaultFolder, IntPtr.Zero, ref riid, out var directoryShellItem) == ErrorCode.S_OK)
                {
                    frm.SetDefaultFolder(directoryShellItem);
                }
            }

            var result = owner == null
                ? frm.Show()
                : frm.Show(owner.Handle);

            if (result == ErrorCode.S_OK &&
                frm.GetResult(out var shellItem) == ErrorCode.S_OK &&
                shellItem.GetDisplayName(SIGDN.FileSysPath, out var pszString) == ErrorCode.S_OK &&
                pszString != IntPtr.Zero)
            {
                try
                {
                    SelectedFolder = Marshal.PtrToStringAuto(pszString);
                    return(DialogBoxResult.OK);
                }
                finally
                {
                    Marshal.FreeCoTaskMem(pszString);
                }
            }

            return(DialogBoxResult.Cancel);
        }
Esempio n. 28
0
        private void FillLocalView(Shell32.Folder folder)
        {

            this.Cursor = Cursors.WaitCursor;

            m_currentFolder = folder;
            // Notify that update begins
            LocalView.BeginUpdate();

            // Erase last view items
            LocalView.Items.Clear();

            // Erase previous lists image
            ImgListViewSmall.Images.Clear();
            ImgListViewLarge.Images.Clear();

            int idImage = 0;

            ListViewItem lvItem = new ListViewItem("..");
            lvItem.Tag = folder;

            LocalView.Items.Add(lvItem);

            Shell32.FolderItems items = folder.Items();

            // Folder enumeration
            foreach (Shell32.FolderItem item in items)
            {
                if (item.IsFolder)
                {
                    AddViewItem(item, ref idImage);
                }
            }

            // Other files 
            foreach (Shell32.FolderItem item in items)
            {
                if (!item.IsFolder)
                {
                    
                    AddViewItem(item, ref idImage);
                }
            }

            // End update view
            LocalView.EndUpdate();

            //ftpc.LocalFolder = folder.Title;

            this.Cursor = Cursors.Default;

        }
Esempio n. 29
0
        public static ImageSource GetImage(string path, int size)
        {
            IntPtr      intPtr      = FileOperation.GetIcon(path, size, size);
            ImageSource imageSource = Imaging.CreateBitmapSourceFromHBitmap(intPtr, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

            if (imageSource != null)
            {
                imageSource.Freeze();
            }
            Shell32.DestroyIcon(intPtr);

            return(imageSource);
        }
Esempio n. 30
0
        public static bool IsConsoleSubsystem(string executablePath)
        {
            if (Environment.OSVersion.Platform != PlatformID.Win32NT)
            {
                // Under UNIX all applications are effectively console.
                return(true);
            }

            var info           = new Shell32.SHFILEINFO();
            var executableType = (uint)Shell32.SHGetFileInfo(executablePath, 0u, ref info, (uint)Marshal.SizeOf(info), Shell32.SHGFI_EXETYPE);

            return(executableType == Shell32.MZ || executableType == Shell32.PE);
        }
Esempio n. 31
0
        private static IShellItem CreateItemWithParent(ShellItem parent, IntPtr pidl)
        {
            if (RunningVista)
            {
                return(Shell32.SHCreateItemWithParent(IntPtr.Zero,
                                                      parent.GetIShellFolder(), pidl, typeof(IShellItem).GUID));
            }
            var impl =
                (ShellItemImpl)parent.ComInterface;

            return(new ShellItemImpl(
                       Shell32.ILCombine(impl.Pidl, pidl), true));
        }
Esempio n. 32
0
        /// <summary>
        /// Provides a default IExtractIcon implementation.
        /// </summary>
        /// <param name="folderIcon">if set to <c>true</c> use a folder icon, otherwise use an item icon.</param>
        /// <param name="interfacePointer">The interface pointer.</param>
        private void ProvideDefaultIExtractIcon(bool folderIcon, out IntPtr interfacePointer)
        {
            //  Create a default extract icon init interface.
            IDefaultExtractIconInit pdxi;

            Shell32.SHCreateDefaultExtractIcon(typeof(IDefaultExtractIconInit).GUID, out pdxi);

            //  Set the normal icon.
            pdxi.SetNormalIcon("shell32.dll", folderIcon ? 4 : 1);

            //  Get the IExtractIconW interface.
            interfacePointer = Marshal.GetComInterfaceForObject(pdxi, typeof(IExtractIconW));
        }
Esempio n. 33
0
        void OnDelete()
        {
            if (File.Exists(FileName))
            {
                if (Shell32.FileOperation(FileName, FileOperationType.Delete, 0) != 0)
                {
                    return;
                }
            }

            // Remove from List
            RemoveRequested?.Invoke();
        }
Esempio n. 34
0
        static KnownFolder CreateFolder(CSIDL csidl, string name)
        {
            StringBuilder path = new StringBuilder(512);

            if (Shell32.SHGetFolderPath(IntPtr.Zero, csidl, IntPtr.Zero, 0, path) == HResult.S_OK)
            {
                return(new KnownFolder(csidl, name, path.ToString()));
            }
            else
            {
                return(new KnownFolder(csidl, name, string.Empty));
            }
        }
Esempio n. 35
0
        ShellItemImpl GetParent()
        {
            IntPtr pidl = Shell32.ILClone(m_Pidl);

            if (Shell32.ILRemoveLastID(pidl))
            {
                return(new ShellItemImpl(pidl, true));
            }
            else
            {
                return(this);
            }
        }
Esempio n. 36
0
 static IShellItem CreateItemFromIDList(IntPtr pidl)
 {
     if (RunningVista)
     {
         return(Shell32.SHCreateItemFromIDList(pidl,
                                               typeof(IShellItem).GUID));
     }
     else
     {
         return(new Interop.VistaBridge.ShellItemImpl(
                    pidl, false));
     }
 }
Esempio n. 37
0
        public static void MinimizeAll()
        {
            Shell32 shell = null;
            IShellDispatch shellDispatch = null;

            try
            {
                shell = new Shell32();
                shellDispatch = (IShellDispatch)shell;
                shellDispatch.MinimizeAll();
            }

            finally
            {
                Release(shellDispatch);
                Release(shell);
            }
        }
Esempio n. 38
0
 // Gets each video in the child folders
 private static void DirSearch(Shell32.Folder sDir)
 {
     // Goes through each folder
     foreach (Shell32.FolderItem2 item in sDir.Items())
     {
         // Finds each file in folder
         string type = (string)item.ExtendedProperty("Type");
         if (type.ToLower().Contains("folder"))
         {
             DirSearch(shell.NameSpace(sDir.GetDetailsOf(item, 180)));
         } else
         {
             if (type.ToLower().Contains("mp3"))
             {
                 Songs w = new Songs((string)item.ExtendedProperty("Name"), sDir.GetDetailsOf(item, 21));
                 windowsSongs.Add(w);
                 //Debug.WriteLine("Title: {0}\n Name: {1}\n Ext: {2}\n\n", sDir.GetDetailsOf(item, 21), (string)item.ExtendedProperty("Name"), (string)item.ExtendedProperty("Type"));
             }
         }
     }
 }
Esempio n. 39
0
        private static string GetTitle(Shell32.Folder shellFolder, Shell32.FolderItem shellFile)
        {
            if (!string.IsNullOrEmpty(shellFolder.GetDetailsOf(shellFile, TITLE)))
                return shellFolder.GetDetailsOf(shellFile, TITLE);

            // return the filename if there's no title
            return shellFolder.GetDetailsOf(shellFile, FILENAME);
        }
Esempio n. 40
0
        private void AddViewItem(Shell32.FolderItem item, ref int idImage)
        {
            string[] sValues = new string[10];

            sValues[0] = item.Name;
            if (item.Size == 0)
                sValues[1] = "";
            else
                sValues[1] = Convert.ToString(item.Size / 1024) + " KB";
            sValues[2] = item.Type;
            sValues[3] = item.ModifyDate.ToString();
            /*
            sValues[4] = item.Path;
            sValues[5] = item.IsBrowsable.ToString();
            sValues[6] = item.IsFileSystem.ToString();
            sValues[7] = item.IsFolder.ToString();
            sValues[8] = item.IsLink.ToString();
            */
            ImgListViewSmall.Images.Add (ExtractIcon.GetIcon(item.Path, true));

            ListViewItem lvItem = new ListViewItem(sValues, idImage++);
            lvItem.Tag = item;
            LocalView.Items.Add (lvItem);
        }
Esempio n. 41
0
		private static TreeNode AddTreeNode(Shell32.FolderItem item, ref int imageCount, ImageList imageList, bool getIcons)
		{
			TreeNode tn = new TreeNode();
			tn.Text = item.Name;
			tn.Tag = item;

			if(getIcons)
			{
				try
				{
					imageCount++;
					tn.ImageIndex = imageCount;
					imageCount++;
					tn.SelectedImageIndex = imageCount;
					imageList.Images.Add(ExtractIcons.GetIcon(item.Path, false, imageList)); // normal icon
					imageList.Images.Add(ExtractIcons.GetIcon(item.Path, true, imageList)); // selected icon
				}
				catch // use default 
				{
					tn.ImageIndex = 1;
					tn.SelectedImageIndex = 2;
				}
			}
			else // use default
			{
				tn.ImageIndex = 1;
				tn.SelectedImageIndex = 2;
			}
			return tn;
		}
 public void StartCopy(Shell32.FolderItem src, Shell32.Folder destFolder)
 {
     destFolder.CopyHere(src, 0 /*4  do not show file copy dialog */);
 }
    public static int AddRootNode(TreeView tree, int imageCount, ImageList imageList, bool getIcons, Shell32.Shell shell32, Shell32.Folder shell32Folder, string rootNodeS)
    {
        Shell32.FolderItems items = shell32Folder.Items();

            tree.Nodes.Clear();
            TreeNode desktop = new TreeNode(rootNodeS, 0, 0);

            // Added in version 1.11
            // add a FolderItem object to the root (Desktop) node tag that corresponds to the DesktopDirectory namespace
            // This ensures that the GetSelectedNodePath will return the actual Desktop folder path when queried.
            // There's possibly a better way to create a Shell32.FolderItem instance for this purpose,
            // but I surely don't know it

            Shell32.Folder dfolder = shell32Folder; //shell32.NameSpace(ShellFolder.DesktopDirectory);
            foreach (Shell32.FolderItem fi in dfolder.ParentFolder.Items())
            {
                if (fi.Name == dfolder.Title)
                {
                    desktop.Tag = fi;
                    break;
                }
            }

            // Add the Desktop root node to the tree
            tree.Nodes.Add(desktop);

            vlozitSLozkuNa = 0;
            // iterate through the Desktop namespace and populate the first level nodes
            foreach (Shell32.FolderItem item in items)
            {

                    TreeNode tn = AddTreeNode(item, ref imageCount, imageList, getIcons);
                    if (item.IsFolder) // this ensures that desktop shortcuts etc are not displayed
                    {
                        desktop.Nodes.Insert(vlozitSLozkuNa, tn);
                        vlozitSLozkuNa++;

                        CheckForSubDirs(tn, imageList);
                        CheckForSubItems(tn, imageCount);
                    }
                    else
                    {
                        desktop.Nodes.Add( tn);
                    }
                //}
            }
            return imageCount;
    }
Esempio n. 44
0
 /// <summary>
 /// Get Shell file or folder info.
 /// </summary>
 private static ShellObject GetInfo(Shell32.FileInfoItemType identifier, string name)
 {
     return GetInfo(identifier, name, 0);
 }
Esempio n. 45
0
 private void                    ProcessFile(Shell32.FolderItem file, Shell32.Folder objFolder)
 {
     Debug.WriteLine("        [Processing File " + file.Path + "]");
     DataRow data = files.NewRow();
     foreach (int id in ColumnListPerID)
     {
         if (id != 26)
             data[objFolder.GetDetailsOf(null, id).Replace("'", "_").Replace("’", "_")] = objFolder.GetDetailsOf(file, id);
     }
     if (string.IsNullOrEmpty(objFolder.GetDetailsOf(file, 26)))
         data[objFolder.GetDetailsOf(null, 26).Replace("'", "_").Replace("’", "_")] = DBNull.Value;
     else
         data[objFolder.GetDetailsOf(null, 26).Replace("'", "_").Replace("’", "_")] = int.Parse(objFolder.GetDetailsOf(file, 26));
     if ((string) data[objFolder.GetDetailsOf(null, 21).Replace("'", "_").Replace("’", "_")] == "")
         data[objFolder.GetDetailsOf(null, 21).Replace("'", "_").Replace("’", "_")] = System.IO.Path.GetFileName(file.Path);
     data["URI"] = new Uri(file.Path);
     data["ID"] = files.Rows.Count + 1;
     files.Rows.Add(data);
 }
        private TreeViewItem CreateTreeItem(Shell32.FolderItem folderItem)
        {
            if (folderItem == null)
            {
                throw new ArgumentNullException("folderItem");
            }

            TreeViewItem tvi = new TreeViewItem();
            //tvi.Header = folderItem.Name;
            tvi.Tag = folderItem;

            StackPanel panel = new StackPanel();
            panel.Orientation = Orientation.Horizontal;
            panel.Margin = new Thickness(1);
            tvi.Header = panel;

            Image image = new Image();
            image.Source = ExtractIcons.GetIcon(folderItem.Path, false, (folderItem.Type == "3½-Inch Floppy Disk" || folderItem.Type == "Floppy Disk Drive"));
            image.Margin = new Thickness(0, 0, 4, 0);

            TextBlock text = new TextBlock();
            text.VerticalAlignment = VerticalAlignment.Center;
            text.Text = folderItem.Name;

            panel.Children.Add(image);
            panel.Children.Add(text);

            return tvi;
        }
Esempio n. 47
0
		public static extern IntPtr SHBrowseForFolder ( ref Shell32.BROWSEINFO bi );
        /// <summary>
        /// Returns an icon for a given file - indicated by the name parameter.
        /// </summary>
        /// <param name="name">Extension or pathname for file.</param>
        /// <param name="size">Large or small</param>
        /// <param name="linkOverlay">Whether to include the link icon</param>
        /// <param name="shfi">Return File Information</param>
        /// <returns>System.Drawing.Icon</returns>
        public static Icon GetFileIcon(string name, IconSize size, bool linkOverlay, ref Shell32.SHFILEINFO shfi)
        {
            name = Environment.ExpandEnvironmentVariables(name);
            shfi = new Shell32.SHFILEINFO();
            Shell32.SHGetFileInfoConstants flags = Shell32.SHGetFileInfoConstants.SHGFI_TYPENAME | Shell32.SHGetFileInfoConstants.SHGFI_DISPLAYNAME | Shell32.SHGetFileInfoConstants.SHGFI_ICON | Shell32.SHGetFileInfoConstants.SHGFI_SHELLICONSIZE | Shell32.SHGetFileInfoConstants.SHGFI_SYSICONINDEX | Shell32.SHGetFileInfoConstants.SHGFI_USEFILEATTRIBUTES;

            if (linkOverlay) flags |= Shell32.SHGetFileInfoConstants.SHGFI_LINKOVERLAY;
            /* Check the size specified for return. */
            if (IconSize.Small == size)
                flags |= Shell32.SHGetFileInfoConstants.SHGFI_SMALLICON;
            else
                flags |= Shell32.SHGetFileInfoConstants.SHGFI_LARGEICON;

            IntPtr hIml = Shell32.SHGetFileInfo(name,
                Shell32.FILE_ATTRIBUTE.NORMAL,
                ref shfi,
                (uint)Marshal.SizeOf(shfi),
                flags);

            if (shfi.hIcon == IntPtr.Zero) return null;
            if (!IconHelper.Utils.IsXpOrAbove()) return GetManagedIcon(shfi.hIcon);
            // Get the System IImageList object from the Shell:
            Guid iidImageList = new Guid("46EB5926-582E-4017-9FDF-E8998DAA0950");
            Shell32.IImageList iImageList = null;
            int ret = Shell32.SHGetImageList(
                (int)size,
                ref iidImageList,
                ref iImageList
                );
            // the image list handle is the IUnknown pointer, but
            // using Marshal.GetIUnknownForObject doesn't return
            // the right value.  It really doesn't hurt to make
            // a second call to get the handle:
            Shell32.SHGetImageListHandle((int)size, ref iidImageList, ref hIml);

            IntPtr hIcon = IntPtr.Zero;
            if (iImageList == null)
            {
                hIcon = Comctl32.ImageList_GetIcon(
                    hIml,
                    shfi.iIcon,
                    (int)Comctl32.ImageListDrawItemConstants.ILD_TRANSPARENT);
            }
            else
            {
                iImageList.GetIcon(
                    shfi.iIcon,
                    (int)Comctl32.ImageListDrawItemConstants.ILD_TRANSPARENT,
                    ref hIcon);
            }
            return hIcon == IntPtr.Zero ? GetManagedIcon(shfi.hIcon) : GetManagedIcon(hIcon);
        }
 public static void CopyItemHereAndRead(Shell32InstanceWrapper shell, string destDir, Shell32.FolderItem src, TimeSpan timeout, CopyReaderDelegate reader)
 {
     var performer = new CopyPerformer();
     performer.Perform(shell, destDir, src, timeout, reader);
 }
 public string GetItem(Shell32.FolderItem2 Item2)
 {
     return "Not implemented";
 }
 /// <summary>
 /// Extract the icon from file, and return icon information
 /// </summary>
 /// <param name="path">File path, 
 /// such as ex: "C:\\Program Files\\NetMeeting\\conf.exe,1".</param>
 /// <param name="size">The desired icon size</param>
 /// <param name="linkOverlay">Whether to include the link icon</param>
 /// <param name="shfi">The icon size</param>
 /// <returns>This method always returns an icon with the especified size and thier information.</returns>
 public static Icon ExtractIconFromFileEx(string path, IconSize size, bool linkOverlay, ref Shell32.SHFILEINFO shfi)
 {
     EmbeddedIconInfo embeddedIcon = GetEmbeddedIconInfo(Environment.ExpandEnvironmentVariables(path));
     //Gets the handle of the icon.
     return GetFileIcon(embeddedIcon.FileName, size, linkOverlay, ref shfi);
 }
 public string GetTitle(Shell32.FolderItem2 item2)
 {
     string title = _objFolder.GetDetailsOf(item2, 0);
     return title;
 }
        /// <summary>
        /// Used to access system folder icons.
        /// </summary>
        /// <param name="size">Specify large or small icons.</param>
        /// <param name="folderType">Specify open or closed FolderType.</param>
        /// <param name="shfi">Return Folder Information</param>
        /// <returns>System.Drawing.Icon</returns>
        public static Icon GetFolderIcon(IconSize size, FolderType folderType, ref Shell32.SHFILEINFO shfi)
        {
            // Need to add size check, although errors generated at present!
            Shell32.SHGetFileInfoConstants flags = Shell32.SHGetFileInfoConstants.SHGFI_TYPENAME | Shell32.SHGetFileInfoConstants.SHGFI_DISPLAYNAME | Shell32.SHGetFileInfoConstants.SHGFI_ICON | Shell32.SHGetFileInfoConstants.SHGFI_USEFILEATTRIBUTES;

            if (FolderType.Open == folderType)
                flags |= Shell32.SHGetFileInfoConstants.SHGFI_OPENICON;

            if (IconSize.Small == size)
                flags |= Shell32.SHGetFileInfoConstants.SHGFI_SMALLICON;
            else
                flags |= Shell32.SHGetFileInfoConstants.SHGFI_LARGEICON;

            IntPtr hIml;
            // Get the folder icon
            shfi = new Shell32.SHFILEINFO();
            if (IconHelper.Utils.IsSevenOrAbove()) // Windows 7 FIX
            {
                hIml = Shell32.SHGetFileInfo(Environment.GetFolderPath(Environment.SpecialFolder.System),
                Shell32.FILE_ATTRIBUTE.DIRECTORY,
                ref shfi,
                (uint)Marshal.SizeOf(shfi),
                flags);
            }
            else
            {
                hIml = Shell32.SHGetFileInfo(null,
                Shell32.FILE_ATTRIBUTE.DIRECTORY,
                ref shfi,
                (uint)Marshal.SizeOf(shfi),
                flags);
            }
            if (shfi.hIcon == IntPtr.Zero) return null;
            if (!IconHelper.Utils.IsXpOrAbove()) return GetManagedIcon(shfi.hIcon);
            // Get the System IImageList object from the Shell:
            Guid iidImageList = new Guid("46EB5926-582E-4017-9FDF-E8998DAA0950");
            Shell32.IImageList iImageList = null;
            int ret = Shell32.SHGetImageList(
                (int)size,
                ref iidImageList,
                ref iImageList
                );

            // the image list handle is the IUnknown pointer, but
            // using Marshal.GetIUnknownForObject doesn't return
            // the right value.  It really doesn't hurt to make
            // a second call to get the handle:
            Shell32.SHGetImageListHandle((int)size, ref iidImageList, ref hIml);
            IntPtr hIcon = IntPtr.Zero;
            if (iImageList == null)
            {
                hIcon = Comctl32.ImageList_GetIcon(
                   hIml,
                   shfi.iIcon,
                   (int)Comctl32.ImageListDrawItemConstants.ILD_TRANSPARENT);
            }
            else
            {
                iImageList.GetIcon(
                   shfi.iIcon,
                   (int)Comctl32.ImageListDrawItemConstants.ILD_TRANSPARENT,
                   ref hIcon);
            }
            return hIcon == IntPtr.Zero ? GetManagedIcon(shfi.hIcon) : GetManagedIcon(hIcon);
        }
Esempio n. 54
0
        private static int RecurseCount(Shell32.FolderItems Source)
        {
            int ItemCount = 0;

            foreach (Shell32.FolderItem item in Source)
            {
                if (item.IsFolder == true)
                {
                    //Add one for this folder
                    ItemCount++;
                    //Then continue walking down the folder tree
                    ItemCount += RecurseCount(((Shell32.Folder)item.GetFolder).Items());
                }
                else
                {
                    //Add one for this file
                    ItemCount++;
                }
            }

            return ItemCount;
        }