private void StartWatcher(ShellObject shellObject)
        {
            if (_watcher != null) { _watcher.Dispose(); }
            eventStack.Children.Clear();

            txtPath.Text = shellObject.ParsingName;

            _watcher = new ShellObjectWatcher(shellObject, chkRecursive.IsChecked ?? true);
            _watcher.AllEvents += AllEventsHandler;

            _watcher.Start();
        }
Ejemplo n.º 2
0
 public void Load(ShellObject shellObject)
 {
     using (var stream = new FileStream(shellObject.ParsingName, FileMode.Open, FileAccess.Read))
     {
         Populate(stream);
     }
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Internal constructor that takes in a parent ShellObject.
        /// </summary>
        /// <param name="shellObject"></param>
        internal ShellThumbnail(ShellObject shellObject)
        {
            if (shellObject == null || shellObject.NativeShellItem == null)
                throw new ArgumentNullException("shellObject");

            shellItemNative = shellObject.NativeShellItem;
        }
Ejemplo n.º 4
0
 public DriveItem(DriveInfo info)
 {
     Name = GetDriveInfoString(info);
     RootDirectory = info.RootDirectory.FullName;
     ShellObject = ShellObject.FromParsingName(RootDirectory);
     IsReady = info.IsReady;
 }
        public ArchiveViewWindow(ShellObject loc, bool IsPreviewPaneEnabled, bool IsInfoPaneEnabled)
        {
            InitializeComponent();

            archive = loc;

            this.Title = "View Archive - " + archive.GetDisplayName(DisplayNameType.Default);

            ShellVView.Child = Explorer;

            Explorer.NavigationOptions.PaneVisibility.Commands = PaneVisibilityState.Hide;
            Explorer.NavigationOptions.PaneVisibility.CommandsOrganize = PaneVisibilityState.Hide;
            Explorer.NavigationOptions.PaneVisibility.CommandsView = PaneVisibilityState.Hide;
            Explorer.NavigationOptions.PaneVisibility.Preview =
                IsPreviewPaneEnabled ? PaneVisibilityState.Show : PaneVisibilityState.Hide;
            Explorer.NavigationOptions.PaneVisibility.Details =
                IsInfoPaneEnabled ? PaneVisibilityState.Show : PaneVisibilityState.Hide;
            Explorer.NavigationOptions.PaneVisibility.Navigation = PaneVisibilityState.Hide;

            Explorer.ContentOptions.FullRowSelect = true;
            Explorer.ContentOptions.CheckSelect = false;
            Explorer.ContentOptions.ViewMode = ExplorerBrowserViewMode.Tile;

            Explorer.NavigationComplete += new EventHandler<NavigationCompleteEventArgs>(Explorer_NavigationComplete);
            Explorer.Navigate(loc);
        }
        /// <summary>
        /// Internal constructor that takes in a parent ShellObject.
        /// </summary>
        /// <param name="shellObject"></param>
        internal ShellThumbnail(ShellObject shellObject)
        {
            if (shellObject == null || shellObject.NativeShellItem == null)
            {
                throw new ArgumentNullException(nameof(shellObject));
            }

            shellItemNative = shellObject.NativeShellItem;
        }
Ejemplo n.º 7
0
 public static string Resolve(ShellObject shellObject, string fullPath)
 {
     if (shellObject == null)
         return fullPath;
     if (shellObject.IsLink)
     {
         var link = ShellLink.FromParsingName(fullPath);
         var shellPath = ((string)shellObject.Properties.GetProperty("System.ParsingPath").ValueAsObject);
        // var shellPath = ((string)shellObject.Properties.GetProperty("System.Link.TargetParsingPath").ValueAsObject);
         //Für .lnk Systemsteuerung/Verwaltung
         return shellPath == shellObject.Name ? fullPath : shellPath;
     }
     return fullPath;
 }
        public void LoadDirectory(ShellObject obj)
        {
            obj.Thumbnail.FormatOption = ShellThumbnailFormatOption.IconOnly;
            obj.Thumbnail.CurrentSize = new Size(16, 16);
            this.PathImage.Source = obj.Thumbnail.BitmapSource;
            this.pathName.Text = obj.GetDisplayName(DisplayNameType.Default);
            this.so = obj;
            path = obj.ParsingName;

            Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)(() =>
            {




                if (obj.ParsingName == KnownFolders.Network.ParsingName || obj.ParsingName.StartsWith(@"\\"))
                {
                    SetChildren(true);
                    grid1.Visibility = System.Windows.Visibility.Visible;
                    MenuBorder.Visibility = System.Windows.Visibility.Visible;

                }
                else
                {
                    try
                    {
                        ShellContainer con = (ShellContainer)obj;
                        List<ShellObject> joe = new List<ShellObject>();
                        foreach (ShellObject item in con)
                        {
                            if (item.IsFolder == true)
                            {
                                if (item.ParsingName.ToLower().EndsWith(".zip") == false && item.ParsingName.ToLower().EndsWith(".cab") == false)
                                {
                                    joe.Add(item);
                                }
                            }
                        }
                        SetChildren(joe.Count > 0);
                    }
                    catch
                    {
                        SetChildren(false);
                    }
                    
                }
            }));

        }
Ejemplo n.º 9
0
 internal static ImageSource GetIcon(ShellObject shell, IconSize size)
 {
     shell.Thumbnail.CurrentSize = new System.Windows.Size(16, 16);
     switch (size)
     {
         case IconSize.ExtraLarge:
             return shell.Thumbnail.LargeBitmapSource;
         case IconSize.Large:
             return shell.Thumbnail.MediumBitmapSource;
         case IconSize.Medium:
             return shell.Thumbnail.SmallBitmapSource;
         case IconSize.Small:
             return shell.Thumbnail.BitmapSource;
     }
     return null;
 }
Ejemplo n.º 10
0
		/// <summary>
		/// Creates the ShellObjectWatcher for the given ShellObject
		/// </summary>
		/// <param name="shellObject">The ShellObject to monitor</param>
		/// <param name="recursive">Whether to listen for changes recursively (for when monitoring a container)</param>
		public ShellObjectWatcher(ShellObject shellObject, bool recursive) {
			if (shellObject == null) {
				throw new ArgumentNullException("shellObject");
			}

			if (_context == null) {
				_context = new SynchronizationContext();
				SynchronizationContext.SetSynchronizationContext(_context);
			}

			_shellObject = shellObject;
			this._recursive = recursive;

			var result = MessageListenerFilter.Register(OnWindowMessageReceived);
			_listenerHandle = result.WindowHandle;
			_message = result.Message;
		}
Ejemplo n.º 11
0
        public ResizeImage(ShellObject file, string height, string width, string imagename)
        {
            InitializeComponent();

            textBlock1.Text = imagename + ": " + file.GetDisplayName(DisplayNameType.Default);
            cvt = new Bitmap(file.ParsingName);
            textBlock2.Text = height + ": " + cvt.Height.ToString();
            textBlock3.Text = width + ": " + cvt.Width.ToString();

            spinner1.Value = 100;

            percsetting = true;

            textBox1.Text = cvt.Width.ToString();
            textBox2.Text = cvt.Height.ToString();

            percsetting = false;
        }
Ejemplo n.º 12
0
 public Photo(string path)
 {
     // Debug.WriteLine("Photo[" + Thread.CurrentThread.ManagedThreadId + "](" + path + ") started...");
     FullPath = path;
     #if STORE_SHELLOBJECT
     _threadId = Thread.CurrentThread.ManagedThreadId;
     _shellObject = ShellObject.FromParsingName(path);
     var x = DateTaken;
     var xx = Camera;
     #else
     // var shellObject = ShellObject.FromParsingName(path);
     using (var shellObject = ShellObject.FromParsingName(path))
     {
         DateTaken = shellObject.Properties.GetProperty<DateTime?>(SystemProperties.System.Photo.DateTaken).Value;
         Camera = new Camera(shellObject);
     }
     #endif
     // Debug.WriteLine("Photo[" + Thread.CurrentThread.ManagedThreadId + "](" + path + ") complete.");
 }
Ejemplo n.º 13
0
 public int GetExifRotationInfo(string path)
 {
     if (!_shellsupport) return 1;
     _shellitem = ShellObject.FromParsingName(path);
     object res = 1;
     foreach (var item in _shellitem.Properties.DefaultPropertyCollection)
     {
         if (item.CanonicalName == "System.Photo.Orientation")
         {
             res = item.ValueAsObject;
             break;
         }
     }
     _shellitem.Dispose();
     _shellitem = null;
     GC.Collect();
     GC.WaitForPendingFinalizers();
     GC.Collect();
     return Convert.ToInt32(res);
 }
Ejemplo n.º 14
0
 public BitmapSource GetThumbnail(string path)
 {
     try
     {
         if (_shellsupport)
         {
             _shellitem = ShellObject.FromParsingName(path);
             BitmapSource ret = _shellitem.Thumbnail.LargeBitmapSource;
             _shellitem.Dispose();
             _shellitem = null;
             GC.Collect();
             GC.WaitForPendingFinalizers();
             GC.Collect();
             return ret;
         }
         else return FailSafeThumbnail(path);
     }
     catch (Exception)
     {
         return FailSafeThumbnail(path);
     }
 }
 internal PropertySystemDevices(ShellObject parent)
 {
     shellObjectParent = parent;
 }
 void IInitializeWithItem.Initialize(object shellItem, Shell.AccessModes accessMode) => _shellObject = ShellObjectFactory.Create((IShellItem)shellItem);
 internal PropertySystemComputer(ShellObject parent)
 {
     shellObjectParent = parent;
 }
        /// <summary>
        ///     Initialize a instance of the <see cref="ShellProperty{T}" /> class.
        /// </summary>
        /// <param name="propertyKey"></param>
        /// <param name="description"></param>
        /// <param name="shellObject"></param>
        /// <remarks>
        ///     This constructor is used in <see cref="ShellPropertyFactory" />.
        ///     Do not change the order of the parameters.
        /// </remarks>
        internal ShellProperty(ShellPropertyKey propertyKey, ShellPropertyDescription description, ShellObject shellObject)
        {
            Contract.Requires <ArgumentNullException>(propertyKey != null);
            Contract.Requires <ArgumentNullException>(shellObject != null);

            this.ShellObject = shellObject;

            this.PropertyKey            = propertyKey;
            this.description            = description;
            this.AllowSetTruncatedValue = false;

            if (this.Description.ValueType != typeof(T))
            {
                throw new InvalidOperationException(
                          String.Format(ErrorMessages.ShellPropertyUnmatchValueType, typeof(T), this.Description.ValueType));
            }
        }
Ejemplo n.º 19
0
        internal static string[] RetrieveData(string file)
        {
            string name, directoryname, fullname, creationtime, lastwritetime;

            FileInfo fileInfo;

            try
            {
                fileInfo      = new FileInfo(file);
                name          = fileInfo.Name;
                directoryname = fileInfo.DirectoryName;
                fullname      = fileInfo.FullName;
                creationtime  = fileInfo.CreationTime.ToString(CultureInfo.CurrentCulture);
                lastwritetime = fileInfo.LastWriteTime.ToString(CultureInfo.CurrentCulture);
            }
            catch (Exception)
            {
                name          = string.Empty;
                directoryname = string.Empty;
                fullname      = string.Empty;
                creationtime  = string.Empty;
                lastwritetime = string.Empty;
            }

            var image = Preloader.Get(Navigation.Pics[Navigation.FolderIndex]).bitmapSource;

            var inchesWidth  = image.PixelWidth / image.DpiX;
            var inchesHeight = image.PixelHeight / image.DpiY;
            var cmWidth      = inchesWidth * 2.54;
            var cmHeight     = inchesHeight * 2.54;

            var    firstRatio  = image.PixelWidth / UILogic.TransformImage.ZoomLogic.GCD(image.PixelWidth, image.PixelHeight);
            var    secondRatio = image.PixelHeight / UILogic.TransformImage.ZoomLogic.GCD(image.PixelWidth, image.PixelHeight);
            string ratioText;

            if (firstRatio == secondRatio)
            {
                ratioText = $"{firstRatio}:{secondRatio} ({Application.Current.Resources["Square"]})";
            }
            else if (firstRatio > secondRatio)
            {
                ratioText = $"{firstRatio}:{secondRatio} ({Application.Current.Resources["Landscape"]})";
            }
            else
            {
                ratioText = $"{firstRatio}:{secondRatio} ({Application.Current.Resources["Portrait"]})";
            }

            object bitdepth, dpiX, dpiY;
            string dpi;

            try
            {
                var so = ShellObject.FromParsingName(file);
                bitdepth = so.Properties.GetProperty(SystemProperties.System.Image.BitDepth).ValueAsObject;
                dpiX     = so.Properties.GetProperty(SystemProperties.System.Image.HorizontalResolution).ValueAsObject;
                dpiY     = so.Properties.GetProperty(SystemProperties.System.Image.VerticalResolution).ValueAsObject;
                so.Dispose();
            }
            catch (Exception)
            {
                bitdepth = string.Empty;
                dpiX     = string.Empty;
                dpiY     = string.Empty;
            }

            if (bitdepth == null)
            {
                bitdepth = string.Empty;
            }

            if (dpiX == null)
            {
                dpi = string.Empty;
            }
            else
            {
                dpi = Math.Round((double)dpiX) + " x " + Math.Round((double)dpiY) + " " + Application.Current.Resources["Dpi"];
            }

            return(new string[]
            {
                // Fileinfo
                name,
                directoryname,
                fullname,
                creationtime,
                lastwritetime,

                // Resolution
                image.PixelWidth + " x " + image.PixelHeight + " " + Application.Current.Resources["Pixels"],

                // DPI
                dpi,

                // Bit dpeth
                bitdepth.ToString(),

                // Megapixels
                ((float)image.PixelHeight * image.PixelWidth / 1000000)
                .ToString("0.##", CultureInfo.CurrentCulture) + " " + Application.Current.Resources["MegaPixels"],

                // Print size cm
                cmWidth.ToString("0.##", CultureInfo.CurrentCulture) + " x " + cmHeight.ToString("0.##", CultureInfo.CurrentCulture)
                + " " + Application.Current.Resources["Centimeters"],

                // Print size inch
                inchesWidth.ToString("0.##", CultureInfo.CurrentCulture) + " x " + inchesHeight.ToString("0.##", CultureInfo.CurrentCulture)
                + " " + Application.Current.Resources["Inches"],

                // Aspect ratio
                ratioText
            });
        }
Ejemplo n.º 20
0
        public static bool CBZExport(string ComicPath, string Format, string OutDirectory = null, string NamePrefix = "")
        {
            var OutDir = OutDirectory ?? SelectDirectory((ShellContainer)ShellObject.FromParsingName(ComicPath), Main.Language);

            if (OutDir == null)
            {
                return(false);
            }

            string IndexPath = null, ChapPath = null;
            bool   ChapsFound = false, IndexFound = false;

            ILanguage ActiveLang = null;

            foreach (var Language in Main.GetLanguagesInstance())
            {
                string PossibleCoverPath   = Path.Combine(ComicPath, Language.Cover) + ".png";
                string PossibleIndexPath   = Path.Combine(ComicPath, Language.Index) + ".html";
                string PossibleChapterPath = Path.Combine(ComicPath, Language.Chapters);
                if (File.Exists(PossibleCoverPath))
                {
                    if (File.Exists(PossibleIndexPath))
                    {
                        IndexPath  = PossibleIndexPath;
                        IndexFound = true;
                        ActiveLang = Language;
                    }
                    if (Directory.Exists(PossibleChapterPath))
                    {
                        ChapPath   = PossibleChapterPath;
                        ChapsFound = true;
                        ActiveLang = Language;
                    }
                }
            }

            if (!ChapsFound || !IndexFound)
            {
                return(false);
            }

            var  Chapters = Directory.GetDirectories(ChapPath);
            bool OneShot  = Chapters.Count() == 1;

            foreach (var Chapter in Chapters)
            {
                var ChapName = Path.GetFileName(Chapter.TrimEnd('\\', '/'));
                var ChapDir  = Format == null ? Chapter : ExportChapter(Chapter, OutDir, Format, ActiveLang);
                if (ChapDir == null)
                {
                    continue;
                }

                if (Format != null && Directory.GetFiles(ChapDir).Length == 0)
                {
                    continue;
                }

                Main.Status    = ActiveLang.Compressing;
                Main.SubStatus = ChapName;

                var FinalChapName = (OneShot ? Path.GetFileName(ComicPath.TrimEnd(' ', '\\', '/')) : ChapName);
                var Output        = Path.Combine(OutDir, NamePrefix + FinalChapName + ".cbz");
                if (File.Exists(Output))
                {
                    return(true);
                }

                CreateCBZ(ChapDir, Output);

                if (Format != null)
                {
                    Directory.Delete(ChapDir, true);
                }
            }

            Main.Status    = ActiveLang.IDLE;
            Main.SubStatus = "";
            return(true);
        }
        /// <summary>
        /// To avoid the 'Dispatcher processing has been suspended' InvalidOperationException on Win7,
        /// the ExplorerBorwser native control is initialized after this control is fully loaded.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void ExplorerBrowser_Loaded( object sender, RoutedEventArgs e )
        {
            // setup timer to update dependency properties from CLR properties of WinForms ExplorerBrowser object
            dtCLRUpdater.Tick += new EventHandler( UpdateDependencyPropertiesFromCLRPRoperties );
            dtCLRUpdater.Interval = new TimeSpan( 100 * 10000 ); // 100ms
            dtCLRUpdater.Start( );

            if (initialNavigationTarget != null )
            {
                ExplorerBrowserControl.Navigate(initialNavigationTarget);
                initialNavigationTarget = null;
            }

            if (initialViewMode != null)
            {
                ExplorerBrowserControl.ContentOptions.ViewMode = (ExplorerBrowserViewMode)initialViewMode;
                initialViewMode = null;
            }
        }
Ejemplo n.º 22
0
        public Card()
        {
            _isTextPresent  = -1;
            _isImagePresent = -1;
            _isVideoPresent = -1;
            _isAudioPresent = -1;
            _isUrlPresent   = -1;

            MetaData = new MetaData();

            MetaData.Color = Colors.White;

            _decals = new ObservableCollection <Decal>();

#if !SILVERLIGHT
            AddText = new DelegateCommand(() =>
            {
                TextDecal decal = new TextDecal();
                AddDecal(decal);

                decal.DelaySelect(true);
            }, CanAddText);

            AddImage = new DelegateCommand <string>((path) =>
            {
                ImageDecal Idecal = new ImageDecal();

                CommonOpenFileDialog cfd = new CommonOpenFileDialog((string)Application.Current.FindResource("Resource_SaveDialogTitle_AddImage"));

                cfd.EnsureReadOnly = true;

                // Set the initial location as the path of the library
                cfd.InitialDirectoryShellContainer = KnownFolders.PicturesLibrary as ShellContainer;

                if (cfd.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    // Get the selection from the user.
                    ShellObject so = cfd.FileAsShellObject;
                    if (so.ParsingName != null)
                    {
                        ((ImageMetaData)Idecal.MetaData).Source = so.ParsingName;
                        AddDecal(Idecal);

                        Idecal.DelaySelect(true);
                    }
                }
            }, CanAddImage);

            AddVideo = new DelegateCommand <string>((path) =>
            {
                CommonOpenFileDialog cfd = new CommonOpenFileDialog((string)Application.Current.FindResource("Resource_SaveDialogTitle_AddVideo"));

                cfd.EnsureReadOnly = true;

                // Set the initial location as the path of the library
                cfd.InitialDirectoryShellContainer = KnownFolders.VideosLibrary as ShellContainer;

                if (cfd.ShowDialog() == CommonFileDialogResult.Ok)
                {
                    // Get the selection from the user.
                    ShellObject so = cfd.FileAsShellObject;
                    if (so.ParsingName != null)
                    {
                        VideoDecal Idecal = new VideoDecal();
                        ((VideoMetaData)Idecal.MetaData).Source = so.ParsingName;
                        AddDecal(Idecal);

                        VideoControlDecal control = new VideoControlDecal(Idecal);

                        Idecal.VideoControl = control;
                        AddDecal(control);

                        Idecal.DelaySelect(true);
                    }
                }
            }, CanAddVideo);

            AddAudio = new DelegateCommand(() =>
            {
                TextToSpeechDecal decal = new TextToSpeechDecal();
                AddDecal(decal);
                decal.DelaySelect(true);
            }, CanAddAudio);

            AddUrl = new DelegateCommand(() =>
            {
                InfoLinkDecal decal = new InfoLinkDecal();
                AddDecal(decal);
                decal.DelaySelect(true);
            }, CanAddUrl);

            RemoveDecal = new DelegateCommand <Decal>((decal) =>
            {
                if (decal == null)
                {
                    decal = SelectedDecal;
                }

                if (decal != null)
                {
                    decal.UnInitialize();
                    DeleteDecal(decal);
                }
            });
#endif
        }
Ejemplo n.º 23
0
        public FileExplorerCommand()
        {
            _uploadService            = new UploadService();
            _canceledDownloads        = new List <Guid>();
            ProcessingEntriesChanged += OnProcessingEntriesChanged;

            _dtpProcessor = new DtpProcessor();
            _dtpProcessor.RegisterFunction("GetRootElements", parameters =>
            {
                var rootEntryCollection = new RootEntryCollection
                {
                    RootDirectories          = DirectoryHelper.GetNamespaceDirectories(),
                    ComputerDirectory        = DirectoryHelper.GetDirectoryEntry(DirectoryInfoEx.MyComputerDirectory, null),
                    ComputerDirectoryEntries = DirectoryHelper.GetComputerDirectoryEntries()
                };

                foreach (var driveInfo in DriveInfo.GetDrives())
                {
                    if (
                        rootEntryCollection.ComputerDirectoryEntries.All(
                            x => x.Path != driveInfo.RootDirectory.FullName))
                    {
                        rootEntryCollection.ComputerDirectoryEntries.Add(
                            DirectoryHelper.GetDirectoryEntry(
                                new DirectoryInfoEx(driveInfo.RootDirectory.FullName), null));
                    }
                }
                return(rootEntryCollection);
            }, typeof(RootEntryCollection), typeof(FileEntry), typeof(DirectoryEntry), typeof(DriveDirectoryEntry),
                                           typeof(ProcessingEntry));
            _dtpProcessor.RegisterFunction("GetDirectories", parameters =>
            {
                var path    = parameters.GetString(0);
                var entries =
                    DirectoryHelper.GetDirectories(new DirectoryInfoEx(path));
                return(entries);
            }, typeof(DriveDirectoryEntry));
            _dtpProcessor.RegisterFunction("GetPathContent", parameters =>
            {
                var directories            = parameters.GetValue <List <string> >(0);
                var requestFirstAllEntries = parameters.GetBool(1);
                var result = new List <List <IFileExplorerEntry> >();

                for (int i = 0; i < directories.Count; i++)
                {
                    var directory = directories[i];
                    if (i == 0 && requestFirstAllEntries)
                    {
                        var list = DirectoryHelper.GetDirectoryEntries(directory);
                        result.Add(list);
                        lock (ProcessingEntriesLock)
                        {
                            if (ProcessingEntries.TryGetValue(directory.NormalizePath(), out var processingEntries))
                            {
                                foreach (var fileExplorerEntry in processingEntries.Cast <IFileExplorerEntry>())
                                {
                                    var existingEntry = list.FirstOrDefault(x => x.Name.Equals(fileExplorerEntry.Name, StringComparison.OrdinalIgnoreCase));
                                    if (existingEntry != null)
                                    {
                                        list.Remove(existingEntry);
                                    }
                                    list.Add(fileExplorerEntry);
                                }
                            }
                        }
                    }
                    else
                    {
                        if (directory.Length > 3)
                        {
                            try
                            {
                                result.Add(DirectoryHelper.GetDirectoriesFast(directory).Cast <IFileExplorerEntry>()
                                           .ToList());
                                continue;
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                        }

                        result.Add(
                            DirectoryHelper.GetDirectories(new DirectoryInfoEx(directory))
                            .Cast <IFileExplorerEntry>()
                            .ToList());
                    }
                }

                return(result);
            }, typeof(PackedDirectoryEntry), typeof(DriveDirectoryEntry), typeof(FileEntry), typeof(ProcessingEntry));
            _dtpProcessor.RegisterFunction("GetDirectory", parameters =>
            {
                var path = parameters.GetString(0);
                return(DirectoryHelper.GetDirectoryEntry(new DirectoryInfoEx(path), null));
            }, typeof(DriveDirectoryEntry));
            _dtpProcessor.RegisterFunction("ExpandEnvironmentVariables",
                                           parameters => Environment.ExpandEnvironmentVariables(parameters.GetString(0)));
            _dtpProcessor.RegisterFunction("RemoveEntries", parameters =>
            {
                var entries    = parameters.GetValue <List <EntryInfo> >(0);
                var failedList = new List <string>();
                foreach (EntryInfo entry in entries)
                {
                    try
                    {
                        if (entry.IsDirectory)
                        {
                            Directory.Delete(entry.Path, true);
                        }
                        else
                        {
                            File.Delete(entry.Path);
                        }
                        failedList.Add(null);
                    }
                    catch (Exception ex)
                    {
                        failedList.Add(ex.Message);
                    }
                }

                return(failedList);
            });
            _dtpProcessor.RegisterProcedure("RenameEntry", parameters =>
            {
                var entry   = parameters.GetValue <EntryInfo>(0);
                var newName = parameters.GetString(1);
                if (entry.IsDirectory)
                {
                    Directory.Move(entry.Path, Path.Combine(Path.GetDirectoryName(entry.Path), newName));
                }
                else
                {
                    File.Move(entry.Path, Path.Combine(Path.GetDirectoryName(entry.Path), newName));
                }
            });
            _dtpProcessor.RegisterProcedure("CreateFolder", parameters =>
            {
                var path = parameters.GetString(0);
                Directory.CreateDirectory(path);
            });
            _dtpProcessor.RegisterProcedure("CreateShortcut", parameters =>
            {
                var path = parameters.GetString(0);
                var info = parameters.GetValue <ShortcutInfo>(1);

                Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8"));
                //Windows Script Host Shell Object
                object shell = Activator.CreateInstance(t);
                try
                {
                    object lnk = t.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shell,
                                                new object[] { path });
                    try
                    {
                        t.InvokeMember("TargetPath", BindingFlags.SetProperty, null, lnk,
                                       new object[] { info.TargetLocation });
                        t.InvokeMember("Description", BindingFlags.SetProperty, null, lnk,
                                       new object[] { info.Description });

                        if (!string.IsNullOrEmpty(info.WorkingDirectory))
                        {
                            t.InvokeMember("WorkingDirectory", BindingFlags.SetProperty, null, lnk,
                                           new object[] { info.WorkingDirectory });
                        }

                        if (!string.IsNullOrEmpty(info.IconPath))
                        {
                            t.InvokeMember("IconLocation", BindingFlags.SetProperty, null, lnk,
                                           new object[] { $"{info.IconPath}, {info.IconIndex}" });
                        }

                        if (info.Hotkey != 0)
                        {
                            //FML
                            var keyByte      = (byte)(info.Hotkey);
                            var modifierByte = (byte)(info.Hotkey >> 8);
                            var key          = (Keys)keyByte;
                            var keys         = new List <string>();

                            const byte HOTKEYF_SHIFT   = 0x01;
                            const byte HOTKEYF_CONTROL = 0x02;
                            const byte HOTKEYF_ALT     = 0x04;

                            if ((modifierByte & HOTKEYF_ALT) == HOTKEYF_ALT)
                            {
                                keys.Add("ALT");
                            }
                            if ((modifierByte & HOTKEYF_CONTROL) == HOTKEYF_CONTROL)
                            {
                                keys.Add("CTRL");
                            }
                            if ((modifierByte & HOTKEYF_SHIFT) == HOTKEYF_SHIFT)
                            {
                                keys.Add("SHIFT");
                            }

                            keys.Add(key.ToString().ToUpper());

                            t.InvokeMember("Hotkey", BindingFlags.SetProperty, null, lnk,
                                           new object[] { string.Join("+", keys.ToArray()) });
                        }

                        t.InvokeMember("Save", BindingFlags.InvokeMethod, null, lnk, null);
                    }
                    finally
                    {
                        Marshal.FinalReleaseComObject(lnk);
                    }
                }
                finally
                {
                    Marshal.FinalReleaseComObject(shell);
                }
            });
            _dtpProcessor.RegisterFunction("GetDirectoryProperties", parameters =>
            {
                var result        = new DirectoryPropertiesInfo();
                var directoryInfo = new DirectoryInfoEx(parameters.GetString(0));
                if (directoryInfo.KnownFolderType != null)
                {
                    result.DirectoryType     = DirectoryType.SpecialFolder;
                    result.SpecialFolderType = (SpecialFolderType)directoryInfo.KnownFolderType.Category;
                }
                var drive = DriveInfo.GetDrives()
                            .FirstOrDefault(x => x.RootDirectory.FullName == directoryInfo.FullName);
                if (drive != null)
                {
                    result.DirectoryType = DirectoryType.Drive;
                    if (drive.IsReady)
                    {
                        result.DriveFormat = drive.DriveFormat;
                    }
                    else
                    {
                        result.DriveFormat = "Not ready";
                    }
                }

                result.CreationTime   = directoryInfo.CreationTimeUtc;
                result.LastAccessTime = directoryInfo.LastAccessTimeUtc;
                result.LastWriteTime  = directoryInfo.LastWriteTimeUtc;
                result.Attributes     = (FileAttributes)directoryInfo.Attributes;

                return(result);
            });
            _dtpProcessor.RegisterFunction("GetFileProperties", parameters =>
            {
                var result   = new FilePropertiesInfo();
                var fileInfo = new FileInfoEx(parameters.GetString(0));
                try
                {
                    result.OpenWithProgramPath = FileHelper.AssocQueryString(AssocStr.Executable,
                                                                             fileInfo.Extension);
                    result.OpenWithProgramName = FileHelper.AssocQueryString(AssocStr.FriendlyAppName,
                                                                             fileInfo.Extension);
                }
                catch (Exception)
                {
                    // ignored
                }
                try
                {
                    result.SizeOnDisk = FileHelper.GetFileSizeOnDisk(fileInfo.FullName);
                }
                catch (Exception)
                {
                    // ignored
                }

                result.Size           = fileInfo.Length;
                result.CreationTime   = fileInfo.CreationTimeUtc;
                result.LastAccessTime = fileInfo.LastAccessTimeUtc;
                result.LastWriteTime  = fileInfo.LastWriteTimeUtc;
                result.Attributes     = (FileAttributes)fileInfo.Attributes;

                result.FileProperties = new List <FileProperty>();

                try
                {
                    var fileShellObject = ShellObject.FromParsingName(fileInfo.FullName);

                    if (fileShellObject != null)
                    {
                        using (fileShellObject)
                        {
                            foreach (var prop in fileShellObject.Properties.DefaultPropertyCollection)
                            {
                                if (string.IsNullOrEmpty(prop.CanonicalName))
                                {
                                    continue;
                                }

                                var valueString = ObjectToString(prop.ValueAsObject);
                                if (string.IsNullOrEmpty(valueString))
                                {
                                    continue;
                                }

                                var shellProperty = new ShellProperty
                                {
                                    Name       = prop.CanonicalName,
                                    FormatId   = prop.PropertyKey.FormatId,
                                    PropertyId = prop.PropertyKey.PropertyId,
                                    Value      = valueString
                                };

                                var propertyNameSplitter = prop.CanonicalName.Split('.');
                                if (propertyNameSplitter.Length < 3)
                                {
                                    shellProperty.Group = FilePropertyGroup.Details;
                                }
                                else
                                {
                                    try
                                    {
                                        shellProperty.Group =
                                            (FilePropertyGroup)
                                            Enum.Parse(typeof(FilePropertyGroup), propertyNameSplitter[1]);
                                    }
                                    catch (Exception)
                                    {
                                        shellProperty.Group = FilePropertyGroup.Details;
                                    }
                                }

                                result.FileProperties.Add(shellProperty);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    // ignored
                }

                try
                {
                    var fileVersionInfo =
                        FileVersionInfo.GetVersionInfo(fileInfo.FullName);

                    foreach (var prop in typeof(FileVersionInfo).GetProperties())
                    {
                        var value = prop.GetValue(fileVersionInfo, null);

                        if (value == null)
                        {
                            continue;
                        }

                        if (prop.PropertyType == typeof(string) && string.IsNullOrEmpty((string)value))
                        {
                            continue;
                        }

                        if (prop.Name.EndsWith("Part"))
                        {
                            continue;
                        }

                        if (prop.PropertyType == typeof(bool) && !(bool)value)
                        {
                            continue;
                        }

                        string valueString;
                        if (value is DateTime)
                        {
                            valueString = ((DateTime)value).ToUniversalTime().ToString(CultureInfo.InvariantCulture);
                        }
                        else
                        {
                            valueString = value.ToString();
                        }

                        if (result.FileProperties.Any(x => x.Value == valueString))
                        {
                            continue;
                        }

                        result.FileProperties.Add(new FileProperty
                        {
                            Name  = prop.Name,
                            Value = valueString,
                            Group = FilePropertyGroup.FileVersionInfo
                        });
                    }
                }
                catch (Exception)
                {
                    // ignored
                }

                var executableExtensions = new[] { ".exe", ".scr", ".com" };

                if (
                    executableExtensions.Any(
                        x => string.Equals(x, fileInfo.Extension, StringComparison.OrdinalIgnoreCase)))
                {
                    try
                    {
                        var assemblyName = AssemblyName.GetAssemblyName(fileInfo.FullName).FullName;
                        result.FileProperties.Add(new FileProperty
                        {
                            Name  = "AssemblyName",
                            Value = assemblyName,
                            Group = FilePropertyGroup.Executable
                        });
                        result.FileProperties.Add(new FileProperty
                        {
                            Name  = "IsAssembly",
                            Value = "True",
                            Group = FilePropertyGroup.Executable
                        });
                    }
                    catch (Exception)
                    {
                        // ignored
                    }

                    try
                    {
                        result.FileProperties.Add(new FileProperty
                        {
                            Name  = "IsTrusted",
                            Value = AuthenticodeTools.IsTrusted(fileInfo.FullName).ToString(),
                            Group = FilePropertyGroup.Executable
                        });
                    }
                    catch (Exception)
                    {
                        // ignored
                    }
                }

                return(result);
            }, typeof(ShellProperty));
            _dtpProcessor.RegisterFunction("CalculateHashValue", parameters =>
            {
                var path = parameters.GetString(0);
                var type = parameters.GetValue <HashValueType>(1);

                HashAlgorithm hashAlgorithm;
                switch (type)
                {
                case HashValueType.MD5:
                    hashAlgorithm = new MD5CryptoServiceProvider();
                    break;

                case HashValueType.SHA1:
                    hashAlgorithm = new SHA1CryptoServiceProvider();
                    break;

                case HashValueType.SHA256:
                    hashAlgorithm = new SHA256CryptoServiceProvider();
                    break;

                case HashValueType.SHA512:
                    hashAlgorithm = new SHA512CryptoServiceProvider();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                using (hashAlgorithm)
                    using (var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
                        return(hashAlgorithm.ComputeHash(fileStream));
            });
            _dtpProcessor.RegisterProcedure("ExecuteFile", parameters =>
            {
                var path           = parameters.GetString(0);
                var arguments      = parameters.GetString(1);
                var verb           = parameters.GetString(2);
                var createNoWindow = parameters.GetBool(3);

                var process = new Process
                {
                    StartInfo =
                    {
                        FileName       = path,
                        Arguments      = arguments,
                        Verb           = verb,
                        CreateNoWindow = createNoWindow
                    }
                };
                process.Start();
            });
            _dtpProcessor.RegisterFunction("RequestFileUpload", parameters =>
            {
                var path      = parameters.GetString(0);
                var hashValue = parameters.GetValue <byte[]>(1);
                var length    = parameters.GetValue <long>(2);

                return(_uploadService.CreateNewUploadProcess(path, hashValue, length));
            });
            _dtpProcessor.RegisterProcedure("CancelFileUpload", parameters =>
            {
                var guid = parameters.GetValue <Guid>(0);
                _uploadService.CancelUpload(guid);
            });
            _dtpProcessor.RegisterFunction("FinishFileUpload", parameters =>
            {
                var guid = parameters.GetValue <Guid>(0);
                return(_uploadService.FinishUpload(guid));
            });
            _dtpProcessor.RegisterFunction("InitializeDownload", parameters =>
            {
                var path        = parameters.GetString(0);
                var isDirectory = parameters.GetBool(1);
                var guid        = parameters.GetValue <Guid>(2);

                FileInfo fileToUpload;
                if (isDirectory)
                {
                    var directory = new DirectoryInfo(path);
                    if (!directory.Exists)
                    {
                        return(new DownloadInformation(DownloadResult.DirectoryNotFound));
                    }

                    fileToUpload = new FileInfo(FileExtensions.GetFreeTempFileName());
                    ResponseByte((byte)FileExplorerCommunication.ResponsePackagingDirectory, _connectionInfo);
                    var fastZip = new FastZip();
                    fastZip.CreateZip(fileToUpload.FullName, directory.FullName, true, null, null);
                }
                else
                {
                    var fi = new FileInfo(path);
                    if (!fi.Exists)
                    {
                        return(new DownloadInformation(DownloadResult.FileNotFound));
                    }

                    fileToUpload = fi.CopyTo(FileExtensions.GetFreeTempFileName());

                    ResponseByte((byte)FileExplorerCommunication.ResponseCopyingFile, _connectionInfo);
                }

                var fileStream = new FileStream(fileToUpload.FullName, FileMode.Open, FileAccess.Read);
                byte[] hash;
                using (var md5CryptoService = new MD5CryptoServiceProvider())
                    hash = md5CryptoService.ComputeHash(fileStream);

                fileStream.Position = 0;
                new Thread(() =>
                {
                    const int bufferSize = 4096;
                    try
                    {
                        using (fileStream)
                        {
                            int read;
                            var guidData = guid.ToByteArray();
                            var buffer   = new byte[bufferSize];

                            while ((read = fileStream.Read(buffer, 0, bufferSize)) > 0)
                            {
                                _connectionInfo.UnsafeResponse(this, read + 17, writer =>
                                {
                                    writer.Write((byte)FileExplorerCommunication.ResponseDownloadPackage);
                                    writer.Write(guidData);
                                    writer.Write(buffer, 0, read);
                                });

                                if (_isDisposed)
                                {
                                    return;
                                }

                                if (_canceledDownloads.Contains(guid))
                                {
                                    _canceledDownloads.Remove(guid);
                                    return;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        if (!_isDisposed)
                        {
                            ResponseBytes((byte)FileExplorerCommunication.ResponseDownloadFailed,
                                          guid.ToByteArray(), _connectionInfo);
                        }
                    }
                    finally
                    {
                        fileToUpload.Delete();
                    }
                }).Start();

                return(new DownloadInformation(fileToUpload.Length, hash));
            });
            _dtpProcessor.RegisterProcedure("CancelDownload", parameters =>
            {
                var downloadGuid = parameters.GetValue <Guid>(0);
                _canceledDownloads.Add(downloadGuid);
            });
            _dtpProcessor.RegisterFunction("DownloadToServer", parameters =>
            {
                var path        = parameters.GetString(0);
                var isDirectory = parameters.GetBool(1);

                if (!isDirectory)
                {
                    var fileInfo = new FileInfo(path);
                    if (!fileInfo.Exists)
                    {
                        return(DownloadResult.FileNotFound);
                    }

                    new Thread(() =>
                    {
                        _connectionInfo.ClientInfo.ClientOperator.DatabaseConnection.PushFile(fileInfo.FullName,
                                                                                              fileInfo.Name, DataMode.File);
                    }).Start();
                }
                else
                {
                    var directoryInfo = new DirectoryInfo(path);
                    if (!directoryInfo.Exists)
                    {
                        return(DownloadResult.DirectoryNotFound);
                    }

                    new Thread(() =>
                    {
                        var tempFile = new FileInfo(FileExtensions.GetFreeTempFileName());
                        var fastZip  = new FastZip();
                        fastZip.CreateZip(tempFile.FullName, directoryInfo.FullName, true, null);

                        _connectionInfo.ClientInfo.ClientOperator.DatabaseConnection.PushFile(tempFile.FullName,
                                                                                              directoryInfo.Name, DataMode.ZipArchive);
                        tempFile.Delete();
                    }).Start();
                }

                return(DownloadResult.Succeed);
            });
            _dtpProcessor.RegisterFunction("GetFileThumbnail", parameters =>
            {
                var filePath = parameters.GetString(0);
                var bigSize  = parameters.GetBool(1);

                var thumbnail = bigSize
                    ? WindowsThumbnailProvider.GetThumbnail(filePath, 300, 169, ThumbnailOptions.BiggerSizeOk)
                    : WindowsThumbnailProvider.GetThumbnail(filePath, 100, 56, ThumbnailOptions.None);

                byte[] data;
                using (var memoryStream = new MemoryStream())
                {
                    thumbnail.Save(memoryStream, ImageFormat.Png);
                    data = memoryStream.ToArray();
                }
                Debug.Print("Thumbnail size: " + data.Length);

                return(data);
            });
            _dtpProcessor.RegisterProcedure("CreateArchive", parameters =>
            {
                var archiveOptions  = parameters.GetValue <ArchiveOptions>(0);
                var processingEntry = new ProcessingEntry
                {
                    Action        = ProcessingEntryAction.Packing,
                    CreationTime  = DateTime.UtcNow,
                    IsInterminate = true,
                    LastAccess    = DateTime.UtcNow,
                    Name          = Path.GetFileName(archiveOptions.ArchivePath),
                    Path          = archiveOptions.ArchivePath,
                    Size          = 0,
                    Progress      = 0
                };

                var normalizedFolderPath = Path.GetDirectoryName(archiveOptions.ArchivePath).NormalizePath();
                var normalizedPath       = archiveOptions.ArchivePath.NormalizePath();

                var cancellationToken = new CancellationTokenEx();

                lock (ProcessingEntriesLock)
                {
                    if (ProcessingEntries.TryGetValue(normalizedFolderPath, out var processingEntries))
                    {
                        processingEntries.Add(processingEntry);
                    }
                    else
                    {
                        ProcessingEntries.Add(normalizedFolderPath, new List <ProcessingEntry> {
                            processingEntry
                        });
                    }

                    ProcessEntryCancellationTokens.Add(normalizedPath, cancellationToken);
                }

                ProcessingEntriesChanged?.Invoke(this,
                                                 new ProcessingEntriesChangedEventArgs(normalizedFolderPath, processingEntry, EntryUpdateMode.Add));

                new Thread(() =>
                {
                    try
                    {
                        ZipUtilities.CreateArchive(archiveOptions, processingEntry, cancellationToken, entry =>
                        {
                            ProcessingEntriesChanged?.Invoke(this,
                                                             new ProcessingEntriesChangedEventArgs(normalizedFolderPath, processingEntry,
                                                                                                   EntryUpdateMode.Update));
                        });
                    }
                    catch (Exception)
                    {
                        cancellationToken.Cancel();
                    }
                    finally
                    {
                        lock (ProcessingEntriesLock)
                        {
                            if (ProcessingEntries.TryGetValue(normalizedFolderPath, out var processingEntries))
                            {
                                processingEntries.Remove(processingEntry);
                                if (processingEntries.Count == 0)
                                {
                                    ProcessingEntries.Remove(normalizedFolderPath);
                                }
                            }

                            ProcessEntryCancellationTokens.Remove(normalizedPath);
                        }
                    }

                    if (cancellationToken.IsCanceled)
                    {
                        try
                        {
                            File.Delete(archiveOptions.ArchivePath);
                        }
                        catch (Exception)
                        {
                            // ignored
                        }

                        return;
                    }

                    if (archiveOptions.DeleteAfterArchiving)
                    {
                        foreach (var entry in archiveOptions.Entries)
                        {
                            try
                            {
                                if (entry.IsDirectory)
                                {
                                    Directory.Delete(entry.Path, true);
                                }
                                else
                                {
                                    File.Delete(entry.Path);
                                }
                            }
                            catch (Exception)
                            {
                                // ignored
                            }
                        }
                    }
                }).Start();
            });
Ejemplo n.º 24
0
 internal PendingNavigation(ShellObject location, int index)
 {
     this.location = location;
     this.index    = index;
 }
Ejemplo n.º 25
0
 public ShellTreeContainerItem(ShellObject shellObj, ShellTreeContainerItem parent, IShellItemsOperation shellItemsOperation) : base(shellObj, parent, shellItemsOperation)
 {
 }
Ejemplo n.º 26
0
 internal PendingNavigation(ShellObject location, int index)
 {
     Location = location;
     Index    = index;
 }
Ejemplo n.º 27
0
        static int ChangeFolder(ShellDebuggerModel model, IntPtr pidl,
                                SBSP wFlags, IShellFolder folderTmp, IntPtr pidlTmp)
        {
            model.currentFolder = folderTmp;
            var Form = model.Form;

            FOLDERSETTINGS fs              = new FOLDERSETTINGS();
            IShellView     lastIShellView  = model.ShellView;
            IShellView2    lastIShellView2 = model.ShellView as IShellView2;

            if (lastIShellView != null)
            {
                lastIShellView.GetCurrentInfo(ref fs);
            }
            // Copy the old folder settings
            else
            {
                fs          = new FOLDERSETTINGS();
                fs.fFlags   = ShellDebuggerModel.folderFlags;
                fs.ViewMode = ShellDebuggerModel.folderViewMode;
            }

            // Create the IShellView
            IntPtr iShellViewPtr;
            var    shellViewGuid = typeof(IShellView).GUID;
            var    hr            = ShellObject.CreateViewObject(folderTmp, Form.Handle,
                                                                ref shellViewGuid, out iShellViewPtr);

            if (hr != WinError.S_OK)
            {
                shellViewGuid = typeof(IShellView).GUID;
                hr            = ShellObject.CreateViewObject(folderTmp, Form.Handle,
                                                             ref shellViewGuid, out iShellViewPtr);
            }

            if (hr == WinError.S_OK)
            {
                model.ShellView = null;
                model.ShellView = (IShellView) // IShellView2
                                  Marshal.GetObjectForIUnknown(iShellViewPtr);
                //if (model.ShellView == null)
                //    model.ShellView = (IShellView)
                //               Marshal.GetObjectForIUnknown(iShellViewPtr);
                // int CreateViewWindow2(SV2CVW2_PARAMS lpParams);

                var  hWndListView = IntPtr.Zero;
                RECT rc           =
                    new RECT(0, 0,
                             Form.ClientSize.Width,
                             Form.ClientSize.Height);

                int res;
                model.lastViewPidl = IntPtr.Zero;
                var shellView = model.ShellView;

                try
                {
                    // Create the actual list view.
                    res = shellView.CreateViewWindow(lastIShellView, ref fs,
                                                     model, ref rc, ref hWndListView);

                    model.hWndListView = hWndListView;
                    shellView.EnableModeless(true);
                }
                catch (COMException)
                {
                    return(WinError.E_FAIL);
                }

                if (res < 0)
                {
                    return(WinError.E_FAIL);
                }

                // Release the old IShellView
                if (lastIShellView != null)
                {
                    lastIShellView.GetCurrentInfo(ref fs);
                    lastIShellView.UIActivate(SVUIA_STATUS.SVUIA_DEACTIVATE);
                    lastIShellView.DestroyViewWindow();
                }

                // Set focus to the IShellView
                model.ShellView.UIActivate(SVUIA_STATUS.SVUIA_ACTIVATE_FOCUS);
                model.currentAbsolutePidl = pidlTmp;

                if (model.lastViewPidl != IntPtr.Zero)
                {
                    //    var lastItem = model.LastSelected;
                }
                //else
                //{
                //    // empty list
                //}
            }

            return(WinError.S_OK);
        }
Ejemplo n.º 28
0
 private string SelectDirectory() => SelectDirectory((ShellContainer)ShellObject.FromParsingName(ChapPath), Language);
 internal PropertySystemIdentityProvider(ShellObject parent)
 {
     shellObjectParent = parent;
 }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            if (args.Length != 1)
            {
                Console.WriteLine("GoPROMP4Renamer <source directory>");
                return;
            }

            var sourceDir = new DirectoryInfo(args[0]);

            if (sourceDir.Exists == false)
            {
                Console.WriteLine($"GoPROMP4Renamer <source> does not exists - [{sourceDir.FullName}]");
                return;
            }

            var fileInfos = sourceDir.EnumerateFiles("*.MP4", SearchOption.AllDirectories).Union(sourceDir.EnumerateFiles("*.JPG", SearchOption.AllDirectories));

            foreach (FileInfo fileInfo in fileInfos)
            {
                DateTime?dateEncoded = null;

                if (string.Equals(fileInfo.Extension, ".MP4", StringComparison.OrdinalIgnoreCase))
                {
                    ShellObject shellObject = ShellObject.FromParsingName(fileInfo.FullName);

                    if (shellObject == null)
                    {
                        Console.WriteLine($"GoPROMP4Renamer - ParsingName for [{fileInfo.Name}] to ShellObject failed.");
                        continue;
                    }

                    dateEncoded = shellObject.Properties.GetProperty(SystemProperties.System.Media.DateEncoded)?.ValueAsObject as DateTime?;

                    if (dateEncoded == null)
                    {
                        Console.WriteLine($"GoPROMP4Renamer - System.Media.DateEncoded for [{fileInfo.Name}] returned null.");
                        continue;
                    }
                }
                else if (string.Equals(fileInfo.Extension, ".JPG", StringComparison.OrdinalIgnoreCase))
                {
                    ShellObject shellObject = ShellObject.FromParsingName(fileInfo.FullName);

                    if (shellObject == null)
                    {
                        Console.WriteLine($"GoPROMP4Renamer - ParsingName for [{fileInfo.Name}] to ShellObject failed.");
                        continue;
                    }

                    dateEncoded = shellObject.Properties.GetProperty(SystemProperties.System.Photo.DateTaken)?.ValueAsObject as DateTime?;

                    if (dateEncoded == null)
                    {
                        Console.WriteLine($"GoPROMP4Renamer - System.Media.DateEncoded for [{fileInfo.Name}] returned null.");
                        continue;
                    }
                }

                if (dateEncoded == null)
                {
                    continue;
                }
                if (fileInfo.DirectoryName == null)
                {
                    continue;
                }

                DateTime mediaCreated = dateEncoded.Value;
                FileInfo newFileInfo  = new FileInfo(Path.Combine(fileInfo.DirectoryName, $"Img{mediaCreated:yyyyMMdd}_{mediaCreated:HHmmss}{fileInfo.Extension}"));

                if (newFileInfo.Exists)
                {
                    Console.WriteLine($"GoPROMP4Renamer - Cannot rename [{fileInfo.Name}] => [{newFileInfo.Name}] - File already exists.");
                    continue;
                }

                try
                {
                    Console.WriteLine($"GoPROMP4Renamer - Rename file [{fileInfo.Name}] => [{newFileInfo.Name}]");
                    fileInfo.MoveTo(newFileInfo.FullName);
                }
                catch (Exception e)
                {
                    Console.WriteLine($"GoPROMP4Renamer - Cannot rename [{fileInfo.Name}] => [{newFileInfo.Name}]");
                    Console.WriteLine($"- Type:{e.GetType()} : {e.Message}{Environment.NewLine}");
                }
            }
        }
 internal PropertySystemJournal(ShellObject parent)
 {
     shellObjectParent = parent;
 }
Ejemplo n.º 32
0
 public CollisionDialog(List <CollisionInfo> _collisions, ShellObject SourceDestination, ShellObject Destination)
 {
     InitializeComponent();
     this.collisions = _collisions;
     Contents        = new ObservableCollection <CollisionItem>();
     foreach (var item in _collisions)
     {
         Contents.Add(new CollisionItem()
         {
             DataContext = item
         });
     }
     this.lblFromfolder.Text = SourceDestination.GetDisplayName(DisplayNameType.Default);
     this.lblTofolder.Text   = Destination.GetDisplayName(DisplayNameType.Default);
     this.DataContext        = this;
 }
Ejemplo n.º 33
0
		/// <summary>
		/// Sets an item to appear as the initial entry in a <b>Save As</b> dialog.
		/// </summary>
		/// <param name="item">The initial entry to be set in the dialog.</param>
		/// <remarks>The name of the item is displayed in the file name edit box, 
		/// and the containing folder is opened in the view. This would generally be 
		/// used when the application is saving an item that already exists.</remarks>
		public void SetSaveAsItem(ShellObject item) {
			if (item == null) {
				throw new ArgumentNullException("item");
			}

			InitializeNativeFileDialog();
			IFileSaveDialog nativeDialog = GetNativeFileDialog() as IFileSaveDialog;

			// Get the native IShellItem from ShellObject
			if (nativeDialog != null) {
				nativeDialog.SetSaveAsItem(item.NativeShellItem);
			}
		}
Ejemplo n.º 34
0
        protected override void WndProc(ref Message m)
        {
            if (m.Msg == (int)WindowsAPI.WndMsg.WM_CONTEXTMENU)
            {
                this.Browser.IsRenameStarted = true;
                ShellObject[]    dirs = this.Browser.SelectedItems.ToArray();
                ContextShellMenu cm1  = new ContextShellMenu(this.Browser, this.Browser.SelectedItems.Count > 0 ? ShellViewGetItemObject.Selection : ShellViewGetItemObject.Background);
                cm1.ShowContextMenu(Cursor.Position);//new System.Drawing.Point(GetCursorPosition().X, GetCursorPosition().Y));
                return;
            }
            if (m.Msg == (int)WindowsAPI.WndMsg.WM_EXITMENULOOP)
            {
                //this.IsRenameStarted = false;
            }
            if (m.Msg == 78)
            {
                //var r = (WindowsAPI.NMHDR*)(IntPtr)lParam;
                WindowsAPI.NMHDR nmhdr = new WindowsAPI.NMHDR();
                nmhdr = (WindowsAPI.NMHDR)m.GetLParam(nmhdr.GetType());
                switch ((int)nmhdr.code)
                {
                case WNM.LVN_GETINFOTIP:
                    //TODO: Write here the code for the tooltip flyout
                    break;

                case WNM.NM_CUSTOMDRAW:
                    if (!this.Browser.NavigationLog.CurrentLocation.IsSearchFolder)
                    {
                        if (nmhdr.hwndFrom == this.SysListviewhandle)
                        {
                            var nmlvcd = WindowsAPI.PtrToStructure <WindowsAPI.NMLVCUSTOMDRAW>(m.LParam);
                            var index  = (int)nmlvcd.nmcd.dwItemSpec;
                            var hdc    = nmlvcd.nmcd.hdc;

                            Guid         IIFV2 = typeof(IShellItem).GUID;
                            IFolderView2 fv2   = this.Browser.GetFolderView2();
                            IShellItem   item  = null;
                            try
                            {
                                fv2.GetItem(index, ref IIFV2, out item);
                            }
                            catch (Exception)
                            {
                            }

                            object      ext     = null;
                            ShellObject itemobj = null;
                            if (item != null)
                            {
                                itemobj = ShellObjectFactory.Create(item);

                                ext = itemobj.Properties.System.FileExtension.Value;
                            }
                            Color?textColor = null;
                            if (this.Browser.LVItemsColorCodes != null && this.Browser.LVItemsColorCodes.Count > 0)
                            {
                                if (ext != null)
                                {
                                    var extItemsAvailable = this.Browser.LVItemsColorCodes.Where(c => c.ExtensionList.Contains(ext.ToString())).Count() > 0;
                                    if (extItemsAvailable)
                                    {
                                        var color = this.Browser.LVItemsColorCodes.Where(c => c.ExtensionList.ToLowerInvariant().Contains(ext.ToString().ToLowerInvariant())).Select(c => c.TextColor).SingleOrDefault();
                                        textColor = color;
                                    }
                                }
                            }

                            switch (nmlvcd.nmcd.dwDrawStage)
                            {
                            case CDDS_PREPAINT:
                                m.Result = (IntPtr)CDRF_NOTIFYITEMDRAW;
                                break;

                            case CDDS_ITEMPREPAINT:
                                // call default procedure in case system might do custom drawing and set special colors

                                if (textColor != null)
                                {
                                    nmlvcd.clrText = ColorTranslator.ToWin32(textColor.Value);
                                    Marshal.StructureToPtr(nmlvcd, m.LParam, false);

                                    m.Result = (IntPtr)(CDRF_NEWFONT | CDRF_NOTIFYPOSTPAINT | CDRF_NOTIFYSUBITEMDRAW);
                                }
                                else
                                {
                                    m.Result = (IntPtr)(CDRF_NOTIFYPOSTPAINT | CDRF_NOTIFYSUBITEMDRAW);
                                }
                                break;

                            case CDDS_ITEMPREPAINT | CDDS_SUBITEM:
                                // before a subitem drawn
                                if ((nmlvcd.nmcd.uItemState & (WindowsAPI.CDIS.HOT | WindowsAPI.CDIS.DROPHILITED)) != 0 || 0 != WindowsAPI.SendMessage(this.SysListviewhandle, WindowsAPI.LVM.GETITEMSTATE, index, (int)WindowsAPI.LVIS.LVIS_SELECTED))
                                {
                                    // hot, drophilited or selected.
                                    if (nmlvcd.iSubItem == 0)
                                    {
                                        // do default to draw hilite bar
                                        m.Result = (IntPtr)CDRF_DODEFAULT;
                                    }
                                    else
                                    {
                                        // remaining region of a hilted item need to be drawn
                                        m.Result = (IntPtr)CDRF_NOTIFYPOSTPAINT;
                                    }
                                }
                                else if ((nmlvcd.iSubItem == 0 && nmlvcd.nmcd.uItemState.HasFlag(WindowsAPI.CDIS.FOCUS)))
                                {
                                    // if the subitem in selected column, or first item with focus
                                    m.Result = (IntPtr)CDRF_NOTIFYPOSTPAINT;
                                }
                                else
                                {
                                    if (textColor != null)
                                    {
                                        nmlvcd.clrText = ColorTranslator.ToWin32(textColor.Value);
                                        Marshal.StructureToPtr(nmlvcd, m.LParam, false);
                                        m.Result = (IntPtr)CDRF_NEWFONT;
                                    }
                                    else
                                    {
                                        m.Result = (IntPtr)CDRF_DODEFAULT;
                                    }
                                }
                                break;

                            case CDDS_ITEMPOSTPAINT:
                                //base.WndProc(ref m);
                                if (nmlvcd.clrTextBk != 0)
                                {
                                    var iconBounds = new WindowsAPI.RECT();

                                    iconBounds.Left = 1;

                                    WindowsAPI.SendMessage(this.SysListviewhandle, WindowsAPI.LVM.GETITEMRECT, index, ref iconBounds);

                                    //using (Graphics graphics = Graphics.FromHdc(nmlvcd.nmcd.hdc))
                                    //{
                                    //  graphics.Clip = new Region(iconBounds.ToRectangle()); ;
                                    //  graphics.FillRectangle(Brushes.Black, new Rectangle(iconBounds.left, iconBounds.bottom - 20, 20, 20));
                                    //}
                                    if (itemobj.IsShared)
                                    {
                                        if (this.Browser.ContentOptions.ViewMode == ExplorerBrowserViewMode.Details || this.Browser.ContentOptions.ViewMode == ExplorerBrowserViewMode.List || this.Browser.ContentOptions.ViewMode == ExplorerBrowserViewMode.SmallIcon)
                                        {
                                            small.DrawOverlay(hdc, 1, new Point(iconBounds.Left, iconBounds.Bottom - 16));
                                        }
                                        else
                                        {
                                            if (this.Browser.ContentOptions.ThumbnailSize > 180)
                                            {
                                                jumbo.DrawOverlay(hdc, 1, new Point(iconBounds.Left, iconBounds.Bottom - this.Browser.ContentOptions.ThumbnailSize / 3), this.Browser.ContentOptions.ThumbnailSize / 3);
                                            }
                                            else
                                            if (this.Browser.ContentOptions.ThumbnailSize > 64)
                                            {
                                                extra.DrawOverlay(hdc, 1, new Point(iconBounds.Left + 10, iconBounds.Bottom - 50));
                                            }
                                            else
                                            {
                                                large.DrawOverlay(hdc, 1, new Point(iconBounds.Left + 10, iconBounds.Bottom - 32));
                                            }
                                        }
                                    }
                                }
                                m.Result = (IntPtr)CDRF_SKIPDEFAULT;
                                break;
                            }
                            if (itemobj != null)
                            {
                                itemobj.Dispose();
                            }
                            return;
                        }
                    }
                    break;
                }
                //base.WndProc(ref m);
            }
            //return;
            // Perform whatever custom processing you must have for this message
            //System.Diagnostics.Debug.WriteLine(m.ToString());
            // forward message to base WndProc
            base.WndProc(ref m);
        }
Ejemplo n.º 35
0
        public static string GetVideoDuration(string filePath) //nice
        {
            using (var shell = ShellObject.FromParsingName(filePath))
            {
                //for the strings later on ..
                string vh;
                string vm;
                string vs;

                //get time from video as timespan (check that file is video before getting here )
                IShellProperty prop    = shell.Properties.System.Media.Duration;
                var            t       = (ulong)prop.ValueAsObject;
                TimeSpan       rawTime = TimeSpan.FromTicks((long)t);

                //only use hours, convert for everything else
                float vidHours   = (float)rawTime.TotalHours;
                float vidMinutes = vidHours * 60;
                float vidSeconds = vidMinutes * 60;

                //convert these to strings
                vh = vidHours.ToString();
                vm = vidMinutes.ToString();
                vs = vidSeconds.ToString();

                //if anything is a single digit, fix that (under 1, under 9) :
                if (vidHours <= 9)
                {
                    if (vidHours <= 1)
                    {
                        //its less than 1, make it 00:
                        vh = "00";
                    }
                    else
                    {
                        //less than 9 (single digit), prepend a 0:
                        vh = "0" + vidHours.ToString();
                    }
                }

                if (vidMinutes <= 9)
                {
                    if (vidMinutes <= 1)
                    {
                        vm = "00";
                    }
                    else
                    {
                        vm = "0" + vidMinutes.ToString();
                    }
                }

                if (vidSeconds <= 9)
                {
                    if (vidSeconds <= 1)
                    {
                        //its less than 1, make it 00:
                        vs = "00";
                    }
                    else
                    {
                        //less than 9 (single digit), prepend a 0:
                        vs = "0" + vidSeconds.ToString();
                    }
                }

                //string vidTime = vh[0].ToString() + vh[1].ToString() + ":" + vm[0].ToString() + vm[1].ToString() + ":" + vs[0].ToString() + vs[1].ToString();  //only get 2 digits, fill in 0's where only 1 number exists

                string vidTime = vh[0].ToString() + vh[1].ToString() + ":" + vm[0].ToString() + vm[1].ToString() + ":" + vs[0].ToString() + vs[1].ToString();  //only get 2 digits, fill in 0's where only 1 number exists


                return(vidTime);
            }
        }
Ejemplo n.º 36
0
        private static ImageSource LoadInternal(string path)
        {
            Logger.WoxDebug($"load from disk {path}");

            ImageSource image;

            if (string.IsNullOrEmpty(path))
            {
                image = GetErrorImage();
                return(image);
            }


            var key = "EmbeddedIcon:";

            if (path.StartsWith(key))
            {
                return(Image.EmbeddedIcon.GetImage(key, path, 32));
            }

            if (path.StartsWith("data:", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    image = new BitmapImage(new Uri(path))
                    {
                        DecodePixelHeight = 32,
                        DecodePixelWidth  = 32
                    };
                }
                catch (Exception e)
                {
                    e.Data.Add(nameof(path), path);
                    Logger.WoxError($"cannot load {path}", e);
                    return(GetErrorImage());
                }

                image.Freeze();
                return(image);
            }

            var normalImage = ImageExtensions.Any(e => path.EndsWith(e));

            if (!Path.IsPathRooted(path) && normalImage)
            {
                path = Path.Combine(Constant.ProgramDirectory, "Images", Path.GetFileName(path));
            }


            var parent1 = new DirectoryInfo(Constant.ProgramDirectory);
            var parent2 = new DirectoryInfo(DataLocation.DataDirectory());
            var subPath = new DirectoryInfo(path);

            Logger.WoxTrace($"{path} {subPath} {parent1} {parent2}");
            var imageInsideWoxDirectory = IsSubDirectory(parent1, subPath) || IsSubDirectory(parent2, subPath);

            if (normalImage && imageInsideWoxDirectory)
            {
                try
                {
                    image = new BitmapImage(new Uri(path))
                    {
                        DecodePixelHeight = 32,
                        DecodePixelWidth  = 32
                    };
                }
                catch (Exception e)
                {
                    e.Data.Add(nameof(path), path);
                    Logger.WoxError($"cannot load {path}", e);
                    return(GetErrorImage());
                }

                image.Freeze();
                return(image);
            }

            if (Directory.Exists(path))
            {
                try
                {
                    // can be extended to support guid things
                    var shell = ShellObject.FromParsingName(path);
                    image = shell.Thumbnail.SmallBitmapSource;
                }
                catch (Exception e)
                {
                    e.Data.Add(nameof(path), path);
                    Logger.WoxError($"cannot load {path}", e);
                    return(GetErrorImage());
                }

                image.Freeze();
                return(image);
            }

            if (File.Exists(path))
            {
                try
                {
                    // https://stackoverflow.com/a/1751610/2833083
                    // https://stackoverflow.com/questions/21751747/extract-thumbnail-for-any-file-in-windows
                    // https://docs.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishellitemimagefactory-getimage
                    var shell = ShellFile.FromFilePath(path);
                    // https://github.com/aybe/Windows-API-Code-Pack-1.1/blob/master/source/WindowsAPICodePack/Shell/Common/ShellThumbnail.cs#L333
                    // https://github.com/aybe/Windows-API-Code-Pack-1.1/blob/master/source/WindowsAPICodePack/Shell/Common/DefaultShellImageSizes.cs#L46
                    // small is (32, 32)
                    image = shell.Thumbnail.SmallBitmapSource;
                    image.Freeze();
                    return(image);
                }
                catch (ShellException e1)
                {
                    try
                    {
                        // sometimes first try will throw exception, but second try will be ok.
                        // so we try twice
                        // Error while extracting thumbnail for C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Steam\\Steam.lnk
                        var shellFile = ShellFile.FromFilePath(path);
                        image = shellFile.Thumbnail.SmallBitmapSource;
                        image.Freeze();
                        return(image);
                    }
                    catch (Exception e2)
                    {
                        Logger.WoxError($"Failed to get thumbnail, first, {path}", e1);
                        Logger.WoxError($"Failed to get thumbnail, second, {path}", e2);
                        image = GetErrorImage();
                        return(image);
                    }
                }
            }

            image = GetErrorImage();
            return(image);
        }
Ejemplo n.º 37
0
        public static void ShowDeleteDialog(string[] sourceItemsCollection, Window win, bool isMoveToRB)
        {
            var confirmationDialog = new FODeleteDialog();

            if (sourceItemsCollection.Count() == 1)
            {
                ShellObject item = ShellObject.FromParsingName(sourceItemsCollection[0]);
                item.Thumbnail.CurrentSize        = new Size(96, 96);
                confirmationDialog.MessageCaption = string.Format("{0} {1}", win.FindResource("btnDeleteCP"),
                                                                  win.FindResource((item.IsLink
                                                                                                                                                                                                                                                                                                                        ? "txtShortcut"
                                                                                                                                                                                                                                                                                                                        : item.IsFolder ? "txtAccusativeFolder" : "txtFile")) as string);
                var itemTypeName =
                    win.FindResource((item.IsLink ? "txtShortcut" : item.IsFolder ? "txtAccusativeFolder" : "txtFile")) as string;
                confirmationDialog.MessageIcon = item.Thumbnail.BitmapSource;
                confirmationDialog.MessageText = isMoveToRB
                                                                                     ? string.Format((string)win.FindResource("txtConfirmDeleteObject"), itemTypeName, win.FindResource("txtRecycleBin"))
                                                                                                                                                                         : string.Format((string)win.FindResource("txtConfirmRemoveObject"), itemTypeName);
                confirmationDialog.FileInfo = item.Name + "\n";
                if (item.IsFolder)
                {
                    confirmationDialog.FileInfo += string.Format("{0}: {1} ", win.FindResource("btnODateCCP") as string,
                                                                 item.Properties.GetProperty("System.DateCreated").ValueAsObject);
                }
                else if (item.IsLink)
                {
                    var targetPath = item.Properties.GetProperty("System.Link.TargetParsingPath").ValueAsObject as string;
                    confirmationDialog.FileInfo += string.Format("{0}: {1}\n({2}) ",
                                                                 win.FindResource("txtLocation") as string, Path.GetFileNameWithoutExtension(targetPath),
                                                                 Path.GetDirectoryName(targetPath));
                }
                else                 // file
                {
                    var fileInfo = string.Format("{0}: {1}\n", win.FindResource("txtType"),
                                                 item.Properties.System.ItemTypeText.ValueAsObject);

                    if (item.Properties.System.ItemAuthors.Value != null)
                    {
                        fileInfo += string.Format("{0}: {1}\n", win.FindResource("btnAuthorCP"),
                                                  string.Join(";", item.Properties.System.ItemAuthors.Value));
                    }
                    string[] sizes = { "B", "KB", "MB", "GB" };
                    var      len   = (ulong)item.Properties.System.Size.ValueAsObject;
                    int      order = 0;
                    while (len >= 1000 && order + 1 < sizes.Length)                     // using SI system, not IEC
                    {
                        order++;
                        len = len / 1000;
                    }
                    // Adjust the format string to your preferences. For example "{0:0.#}{1}" would
                    // show a single decimal place, and no space.
                    string result = String.Format("{0:0.##} {1}", len, sizes[order]);
                    fileInfo += string.Format("{0}: {1}\n", win.FindResource("txtFileSize"), result);
                    fileInfo += string.Format("{0}: {1}\n", win.FindResource("btnODateModCP") as string,
                                              item.Properties.GetProperty("System.DateModified").ValueAsObject);
                    confirmationDialog.FileInfo += fileInfo;
                }
            }
            else
            {
                confirmationDialog.MessageCaption = win.FindResource("txtDeleteSeveralItems") as string;
                confirmationDialog.MessageText    = isMoveToRB
                                                                                                                                                                         ? string.Format((string)win.FindResource("txtConfirmDeleteObjects"), sourceItemsCollection.Count())
                                                                                                                                                                         : string.Format((string)win.FindResource("txtConfirmRemoveObjects"), sourceItemsCollection.Count());
            }

            confirmationDialog.Owner = win;
            if (confirmationDialog.ShowDialog() == true)
            {
                var tempWindow =
                    new Shell.FileOperations.FileOperation(sourceItemsCollection, String.Empty, OperationType.Delete, isMoveToRB);
                var currentDialog = win.OwnedWindows.OfType <FileOperationDialog>().SingleOrDefault();

                if (currentDialog == null)
                {
                    currentDialog             = new FileOperationDialog();
                    tempWindow.ParentContents = currentDialog;
                    currentDialog.Owner       = win;

                    tempWindow.Visibility = Visibility.Collapsed;
                    currentDialog.Contents.Add(tempWindow);
                }
                else
                {
                    tempWindow.ParentContents = currentDialog;
                    tempWindow.Visibility     = Visibility.Collapsed;
                    currentDialog.Contents.Add(tempWindow);
                }
            }
        }
Ejemplo n.º 38
0
 public void SetIcon(ShellObject obj)
 {
     obj.Thumbnail.CurrentSize = new System.Windows.Size(128, 128);
     pbIcon.Image = BitmapSourceToBitmap2(obj.Thumbnail.BitmapSource);
 }
Ejemplo n.º 39
0
 internal ShellProperties(ShellObject parent)
 {
     ParentShellObject = parent;
 }
        void NavigateExplorerBrowser(object sender, SelectionChangedEventArgs args)
        {
            IKnownFolder folder = (IKnownFolder)((ListBox)sender).SelectedItem ?? (IKnownFolder)ShellObject.FromParsingName(KnownFolders.Desktop.ParsingName);

            UpdateProperties(folder);
        }
Ejemplo n.º 41
0
        public void DriversSelectionChanged(object x)
        {
            TreeOfFolders.Clear();
            try
            {
                foreach (DirectoryInfo dir in new DirectoryInfo(x.ToString()).GetDirectories().OrderBy(y => y.Name).ToArray())
                {
                    ShellObject  shellFolder = ShellObject.FromParsingName(dir.FullName.ToString());
                    BitmapSource shellThumb  = shellFolder.Thumbnail.SmallBitmapSource;

                    Folder folder = new Folder
                    {
                        Name     = dir.ToString(),
                        Icon     = shellThumb,
                        FullName = dir.FullName,
                    };
                    try
                    {
                        folder.CountOfFolders = new DirectoryInfo(dir.FullName).GetDirectories().Length.ToString();
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        folder.CountOfFolders = "Отказано в доступе";
                    }

                    try
                    {
                        folder.CountOfFiles = new DirectoryInfo(dir.FullName).GetFiles().Length.ToString();
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        folder.CountOfFiles = "Отказано в доступе";
                    }

                    try
                    {
                        folder.CreationTime = dir.CreationTime.ToString(CultureInfo.InvariantCulture);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                    }

                    folder.Children.Add(new Folder
                    {
                        Name     = "*",
                        Icon     = null,
                        FullName = dir.FullName
                    });

                    TreeOfFolders.Add(folder);
                }


                foreach (FileInfo file in new DirectoryInfo(x.ToString()).GetFiles().OrderBy(y => y.Name).ToArray())
                {
                    Icon icon =
                        (System.Drawing.Icon)System.Drawing.Icon.ExtractAssociatedIcon(file.FullName.ToString());


                    if (file.Extension.ToLower() == ".jpg" || file.Extension.ToLower() == ".jpeg" || file.Extension.ToLower() == ".bmp" || file.Extension.ToLower() == ".png")
                    {
                        TreeOfFolders.Add(
                            new CustomImage
                        {
                            Name         = file.ToString(),
                            Icon         = icon.ToImageSource(),
                            FullName     = file.FullName.ToString(),
                            Size         = ByteSize.FromBytes(file.Length).ToString(),
                            CreationTime = file.CreationTime.ToString(CultureInfo.InvariantCulture)
                        }
                            );
                    }
                    else
                    {
                        TreeOfFolders.Add(
                            new CustomFile
                        {
                            Name         = file.ToString(),
                            Icon         = icon.ToImageSource(),
                            FullName     = file.FullName.ToString(),
                            Size         = ByteSize.FromBytes(file.Length).ToString(),
                            CreationTime = file.CreationTime.ToString(CultureInfo.InvariantCulture)
                        }
                            );
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(@ex.Message);
            }
        }
 /// <summary>
 /// Creates a generic ShellProperty.
 /// </summary>
 /// <param name="propKey">PropertyKey</param>
 /// <param name="shellObject">Shell object from which to get property</param>
 /// <returns>ShellProperty matching type of value in property.</returns>
 public static IShellProperty CreateShellProperty(PropertyKey propKey, ShellObject shellObject)
 {
     return(GenericCreateShellProperty(propKey, shellObject));
 }
 internal PropertySystemContact(ShellObject parent)
 {
     shellObjectParent = parent;
 }
Ejemplo n.º 44
0
 internal PendingNavigation(ShellObject location, int index)
 {
     Location = location;
     Index = index;
 }
 internal PropertySystemDocument(ShellObject parent)
 {
     shellObjectParent = parent;
 }
Ejemplo n.º 46
0
        //New tab from ShellObject
        private void NewTab(ShellObject navTarget)
        {
            //Add a delay for creating new tabs
            System.Timers.Timer aTimer = new System.Timers.Timer();
            aTimer.Interval = 500;
            aTimer.Elapsed += new ElapsedEventHandler(delegate(object source, ElapsedEventArgs e) {
                tabCreateEnabled = true;
            });
            aTimer.Enabled = true;

            if (!tabCreateEnabled)
            {
                tabControl.SelectedIndex = tabControl.Items.Count - 1;
            }
            else {
                tabCreateEnabled = false;

                ExplorerBrowser expBrowser = new ExplorerBrowser();
                expBrowser.HorizontalAlignment = HorizontalAlignment.Left;
                expBrowser.VerticalAlignment = VerticalAlignment.Top;
                expBrowser.Height = (this.Height - 57) > 0 ? (this.Height - 57) : this.Height;
                expBrowser.Width = this.Width;
                expBrowser.NavigationTarget = navTarget;
                expBrowser.AllowDrop = true;
                expBrowser.ViewMode = ExplorerBrowserViewMode.Icon;

                StackPanel expPanel = new StackPanel();
                expPanel.HorizontalAlignment = HorizontalAlignment.Stretch;
                expPanel.VerticalAlignment = VerticalAlignment.Stretch;
                expPanel.Margin = new Thickness(-5, 0, 0, 0);
                expPanel.Background = new SolidColorBrush(Color.FromRgb(245, 246, 247));

                WrapPanel expControls = new WrapPanel();
                expControls.Height = 34;
                expControls.Width = this.Width;

                Button backButton = new Button()
                {
                    Width = 29,
                    Height = 29,
                    Margin = new Thickness(32, 0, 12, 0),
                    VerticalAlignment = VerticalAlignment.Center,
                    Template = (ControlTemplate)FindResource("GlassButton"),
                    Content = new Image()
                    {
                        Width = 29, //back: 20
                        Height = 29, //back: 20
                        VerticalAlignment = VerticalAlignment.Center,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        Source = new BitmapImage(new Uri("pack://application:,,,/images/back2.ico"))
                    }
                };

                Button forwardButton = new Button()
                {
                    Width = 29,
                    Height = 29,
                    Margin = new Thickness(12, 0, 12, 0),
                    VerticalAlignment = VerticalAlignment.Center,
                    Template = (ControlTemplate)FindResource("GlassButton"),
                    Content = new Image()
                    {
                        Width = 29, //forward: 20
                        Height = 29, //forward: 20
                        VerticalAlignment = VerticalAlignment.Center,
                        HorizontalAlignment = HorizontalAlignment.Center,
                        Source = new BitmapImage(new Uri("pack://application:,,,/images/forward2.ico"))
                    }
                };

                TextBox addressBar = new TextBox() {
                    VerticalAlignment = VerticalAlignment.Center,
                    Width = this.Width - 250,
                    Margin = new Thickness(29, 3, 0, 0),
                    AcceptsReturn = false
                };

                forwardButton.PreviewMouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs e)
                {
                    expBrowser.NavigationLogIndex += 1;
                };

                backButton.PreviewMouseLeftButtonDown += delegate(object sender, MouseButtonEventArgs e)
                {
                    expBrowser.NavigationLogIndex -= 1;
                };

                addressBar.KeyDown += delegate(object sender, KeyEventArgs e)
                {
                    if (e.Key == Key.Enter || e.Key == Key.Return)
                    {
                        tryNavigate(expBrowser, addressBar);
                    }
                };

                addressBar.LostKeyboardFocus += delegate(object sender, KeyboardFocusChangedEventArgs e) {
                    try
                    {
                        expBrowser.NavigationTarget = ShellObject.FromParsingName(addressBar.Text);
                    }
                    catch (Exception _e)
                    {
                        addressBar.Text = expBrowser.NavigationTarget.ParsingName;
                    }
                };

                expControls.Children.Add(backButton);
                expControls.Children.Add(forwardButton);
                expControls.Children.Add(addressBar);

                expPanel.Children.Add(expControls);
                expPanel.Children.Add(expBrowser);

                CloseableTabItem tabItem = new CloseableTabItem()
                {
                    MinWidth = 100,
                    HorizontalAlignment = HorizontalAlignment.Stretch,
                    VerticalAlignment = VerticalAlignment.Stretch,
                    Content = expPanel,
                    Header = "Test1",
                };

                tabControl.Items.Add(tabItem);
                tabControl.SelectedIndex = tabControl.Items.Count - 1;

                expBrowser.Loaded += delegate(object sender, RoutedEventArgs e)
                {
                    tabItem.Header = expBrowser.NavigationTarget.Name;
                };

                expBrowser.ExplorerBrowserControl.NavigationComplete +=
                delegate(object sender, Microsoft.WindowsAPICodePack.Controls.NavigationCompleteEventArgs e)
                {
                    tabItem.Header = e.NewLocation.Name;
                    addressBar.Text = e.NewLocation.ParsingName;

                    if (expBrowser.ExplorerBrowserControl.NavigationLog.CanNavigateBackward) {
                        backButton.IsEnabled = true;
                    } else {
                        backButton.IsEnabled = false;
                    }

                    if (expBrowser.ExplorerBrowserControl.NavigationLog.CanNavigateForward) {
                        forwardButton.IsEnabled = true;
                    } else {
                        forwardButton.IsEnabled = false;
                    }
                };

                browsers.Add(tabItem, expBrowser);
            }
        }
 internal PropertySystemImage(ShellObject parent)
 {
     shellObjectParent = parent;
 }
Ejemplo n.º 48
0
		/// <summary>
		/// Creates and initializes the native ExplorerBrowser control
		/// </summary>
		protected override void OnCreateControl() {
			base.OnCreateControl();

			if (this.DesignMode == false) {
				explorerBrowserControl = new ExplorerBrowserClass();

				// hooks up IExplorerPaneVisibility and ICommDlgBrowser event notifications
				ExplorerBrowserNativeMethods.IUnknown_SetSite(explorerBrowserControl, this);

				// hooks up IExplorerBrowserEvents event notification
				explorerBrowserControl.Advise(
					Marshal.GetComInterfaceForObject(this, typeof(IExplorerBrowserEvents)),
					out eventsCookie);

				// sets up ExplorerBrowser view connection point events
				viewEvents = new ExplorerBrowserViewEvents(this);

				NativeRect rect = new NativeRect();
				rect.Top = ClientRectangle.Top;
				rect.Left = ClientRectangle.Left;
				rect.Right = ClientRectangle.Right;
				rect.Bottom = ClientRectangle.Bottom;

				explorerBrowserControl.Initialize(this.Handle, ref rect, null);

				// Force an initial show frames so that IExplorerPaneVisibility works the first time it is set.
				// This also enables the control panel to be browsed to. If it is not set, then navigating to 
				// the control panel succeeds, but no items are visible in the view.
				explorerBrowserControl.SetOptions(ExplorerBrowserOptions.ShowFrames);

				explorerBrowserControl.SetPropertyBag(propertyBagName);

				if (antecreationNavigationTarget != null) {
					BeginInvoke(new MethodInvoker(
					delegate {
						Navigate(antecreationNavigationTarget);
						antecreationNavigationTarget = null;
					}));
				}
			}

			Application.AddMessageFilter(this);
		}
Ejemplo n.º 49
0
 /// <summary>
 /// Creates a generic ShellProperty.
 /// </summary>
 /// <param name="propKey">PropertyKey</param>
 /// <param name="shellObject">Shell object from which to get property</param>
 /// <returns>ShellProperty matching type of value in property.</returns>
 public static IShellProperty CreateShellProperty(PropertyKey propKey, ShellObject shellObject) => GenericCreateShellProperty(propKey, shellObject);
Ejemplo n.º 50
0
        void DoAction(string[] args)
        {
            if (args.Length == 0 || args[0].Contains("?"))
            {
                Usage();
                return;
            }


            if (args[0].Equals("-get", StringComparison.InvariantCultureIgnoreCase))
            {
                if (args.Length != 3)
                {
                    Usage();
                    return;
                }
                string propertyName = args[1];
                string fileName     = Path.GetFullPath(args[2]);

                IShellProperty prop = ShellObject.FromParsingName(fileName).Properties.GetProperty(propertyName);

                DisplayPropertyValue(prop);
            }
            else if (args[0].Equals("-set", StringComparison.InvariantCultureIgnoreCase))
            {
                if (args.Length != 4)
                {
                    Usage();
                    return;
                }
                string propertyName = args[1];
                string value        = args[2];
                string fileName     = Path.GetFullPath(args[3]);

                IShellProperty prop = ShellObject.FromParsingName(fileName).Properties.GetProperty(propertyName);
                SetPropertyValue(value, prop);
            }
            else if (args[0].Equals("-info", StringComparison.InvariantCultureIgnoreCase))
            {
                if (args.Length != 2)
                {
                    Usage();
                    return;
                }
                string propertyName = args[1];
                ShellPropertyDescription propDesc = SystemProperties.GetPropertyDescription(propertyName);
                ShowPropertyInfo(propertyName, propDesc);
            }
            else if (args[0].Equals("-enum", StringComparison.InvariantCultureIgnoreCase))
            {
                if (args.Length < 2)
                {
                    Usage();
                    return;
                }
                string fileName = null;
                string filter   = null;
                if (args.Length > 2)
                {
                    filter   = args[1];
                    fileName = Path.GetFullPath(args[2]);
                }
                else
                {
                    fileName = Path.GetFullPath(args[1]);
                }

                EnumProperties(fileName, filter);
            }
            else
            {
                Usage();
                return;
            }
        }
Ejemplo n.º 51
0
 /// <summary>
 /// Clears the Explorer Browser of existing content, fills it with
 /// content from the specified container, and adds a new point to the Travel Log.
 /// </summary>
 /// <param name="shellObject">The shell container to navigate to.</param>
 /// <exception cref="System.Runtime.InteropServices.COMException">Will throw if navigation fails for any other reason.</exception>
 public void Navigate(ShellObject shellObject)
 {
     if (explorerBrowserControl == null)
     {
         antecreationNavigationTarget = shellObject;
     }
     else
     {
         HRESULT hr = explorerBrowserControl.BrowseToObject(shellObject.NativeShellItem, 0);
         if (hr != HRESULT.S_OK)
         {
             if (hr == HRESULT.RESOURCE_IN_USE)
             {
                 if (NavigationFailed != null)
                 {
                     NavigationFailedEventArgs args = new NavigationFailedEventArgs();
                     args.FailedLocation = shellObject;
                     NavigationFailed(this, args);
                 }
             }
             else
                 throw new COMException("BrowseToObject failed", (int)hr);
         }
     }
 }
 void IInitializeWithItem.Initialize(Shell.IShellItem shellItem, Shell.AccessModes accessMode)
 {
     _shellObject = ShellObjectFactory.Create(shellItem);
 }
Ejemplo n.º 53
0
		/// <summary>
		/// Clears the Explorer Browser of existing content, fills it with
		/// content from the specified container, and adds a new point to the Travel Log.
		/// </summary>
		/// <param name="shellObject">The shell container to navigate to.</param>
		/// <exception cref="System.Runtime.InteropServices.COMException">Will throw if navigation fails for any other reason.</exception>
		public void Navigate(ShellObject shellObject) {
			if (shellObject == null) {
				throw new ArgumentNullException("shellObject");
			}

			if (explorerBrowserControl == null) {
				antecreationNavigationTarget = shellObject;
			} else {
				HResult hr = explorerBrowserControl.BrowseToObject(shellObject.NativeShellItem, 0);
				if (hr != HResult.Ok) {
					if ((hr == HResult.ResourceInUse || hr == HResult.Canceled) && NavigationFailed != null) {
						NavigationFailedEventArgs args = new NavigationFailedEventArgs();
						args.FailedLocation = shellObject;
						NavigationFailed(this, args);
					} else {
						throw new CommonControlException(LocalizedMessages.ExplorerBrowserBrowseToObjectFailed, hr);
					}
				}
			}
		}
Ejemplo n.º 54
0
        private int GetAndCheckValues(string fileName, State state, bool useCodePack = false)
        {
            int errors = 0;
            CPropertyHandler handler = null;

            if (!useCodePack)
            {
                handler = new CPropertyHandler();
                handler.Initialize(fileName, 0);
            }

            foreach (var saved in savedProps)
            {
                IShellProperty prop = ShellObject.FromParsingName(fileName).Properties.GetProperty(saved.Name);

                object objVal;
                if (useCodePack)
                {
                    objVal = prop.ValueAsObject;
                }
                else
                {
                    var value = new PropVariant();
                    handler.GetValue(new TestDriverCodePack.PropertyKey(prop.PropertyKey.FormatId, prop.PropertyKey.PropertyId), value);
                    objVal = value.Value;
                }

                bool bSame = false;
                Type t     = objVal != null?objVal.GetType() : null;

                if (t == typeof(Int16) || t == typeof(Int32) || t == typeof(UInt16) || t == typeof(UInt32) || t == typeof(bool))
                {
                    bSame = objVal.Equals(saved.Value);
                }
                else if (t == typeof(string))
                {
                    bSame = (string)objVal == (string)saved.Value;
                }
                else if (t == typeof(string[]))
                {
                    string[] oss = (string[])objVal;
                    string[] sss = (string[])saved.Value;
                    bSame = true;
                    if (oss.Length == sss.Length)
                    {
                        for (int i = 0; i < oss.Length; i++)
                        {
                            if (oss[i] != sss[i])
                            {
                                bSame = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        bSame = false;
                    }
                }
                else if (t == typeof(Int32[]) || t == typeof(UInt32[]))
                {
                    int[] os = (int[])objVal;
                    int[] ss = (int[])saved.Value;
                    bSame = true;
                    if (os.Length == ss.Length)
                    {
                        for (int i = 0; i < os.Length; i++)
                        {
                            if (!os[i].Equals(ss[i]))
                            {
                                bSame = false;
                                break;
                            }
                        }
                    }
                    else
                    {
                        bSame = false;
                    }
                }
                else if (t == typeof(DateTime))
                {
                    DateTime save = (DateTime)(saved.Value);
                    DateTime read = (DateTime)objVal;

                    // Compare this way because exact ticks don't survive a round trip to text, and legibility
                    // is more useful than serializing just a number of ticks
                    bSame = save.Year == read.Year && save.Month == read.Month && save.Day == read.Day &&
                            save.Hour == read.Hour && save.Minute == read.Minute && save.Second == read.Second &&
                            save.Millisecond == read.Millisecond;
                }
                else
                {
                    bSame = (saved.Value == null && objVal == null);
                }

                if (!bSame)
                {
                    state.RecordEntry(String.Format("Mismatch for property {0}: expected {1}, got {2}", saved.Name,
                                                    saved.Value != null ? ToDisplayString(saved.Value) : "Null", objVal != null ? ToDisplayString(objVal) : "Null"));
                    errors++;
                }
            }

            if (!useCodePack)
            {
                Marshal.ReleaseComObject(handler);  // preempt GC for CCW
            }
            return(errors);
        }
Ejemplo n.º 55
0
        void explorerBrowser1_SelectionChanged(object sender, EventArgs e)
        {
            if (this.explorerBrowser1.SelectedItems != null && this.explorerBrowser1.SelectedItems.Count == 1)
            {
                // Set our new current item
                currentItem = explorerBrowser1.SelectedItems[0];

                // Update preview
                UpdatePreview();
            }
        }
Ejemplo n.º 56
0
        public override bool RunBody(State state)
        {
            RequirePropertyHandlerRegistered();
            RequireContextHandlerRegistered();
            RequireExtHasHandler(extension);

            state.RecordEntry(String.Format("Starting mass property setting on '{0}'...", extension));

            //Create a temp file to put metadata on
            string fileName = CreateFreshFile(1, extension);

            savedProps = new List <SavedProp>();

            // Give all writable properties random values, according to their type
            foreach (var propDesc in state.PropertyDescriptions.Where(p => !p.TypeFlags.HasFlag(TestDriverCodePack.PropertyTypeOptions.IsInnate)))
            {
                // These properties don't seem to be writeable.  Don't know why, but they don't appear anyway in the list
                // of usable properties at http://msdn.microsoft.com/en-us/library/windows/desktop/dd561977(v=vs.85).aspx
                if (propDesc.CanonicalName == "System.History.UrlHash" ||
                    propDesc.CanonicalName == "System.DuiControlResource" ||
                    propDesc.CanonicalName == "System.OfflineFiles.CreatedOffline" ||
                    propDesc.CanonicalName == "System.PropList.XPDetailsPanel" ||
                    propDesc.CanonicalName == "System.SDID" ||
                    propDesc.CanonicalName == "Windows.Registry.Type")
                {
                    continue;
                }

                // Use API Code Pack to set the value, except for strings, because the Code Pack blows when setting strings of length 1 !!
                // Still use Code Pack elsewhere for its nullable type handling
                IShellProperty prop = ShellObject.FromParsingName(fileName).Properties.GetProperty(propDesc.CanonicalName);
                SetPropertyValue(fileName, propDesc, prop);
            }
            state.RecordEntry(String.Format("{0} property values set on {1}", savedProps.Count, fileName));

            // Go around again, using the Handler directly to read all the values written and then check them
            int errors = GetAndCheckValues(fileName, state);

            state.RecordEntry(String.Format("{0} properties read back, {1} mismatches", savedProps.Count, errors));

            if (errors > 0)
            {
                return(false);
            }

            // Use ContextHandler to export all the values
            var contextHandler = new CContextMenuHandler();
            var dobj           = new DataObject();

            dobj.SetFileDropList(new StringCollection {
                fileName
            });
            contextHandler.Initialize(new IntPtr(0), dobj, 0);
            contextHandler.QueryContextMenu(0, 0, 0, 0, 0); // This fails, but  that's ok

            //export the metadata
            CMINVOKECOMMANDINFOEX cmd = new CMINVOKECOMMANDINFOEX();

            cmd.lpVerb = new IntPtr((int)ContextMenuVerbs.Export);
            var cw = new CommandWrapper(cmd);

            contextHandler.InvokeCommand(cw.Ptr);

            Marshal.ReleaseComObject(contextHandler);  // preempt GC for CCW

            // Create new file and import values to it
            string fileName2 = CreateFreshFile(2, extension);

            // rename metadata file
            RenameWithDelete(MetadataFileName(fileName), MetadataFileName(fileName2));
            state.RecordEntry("Metadata exported, starting to import onto new file and check...");

            // Get a new handler and import
            contextHandler = new CContextMenuHandler();
            dobj           = new DataObject();
            dobj.SetFileDropList(new StringCollection {
                fileName2
            });
            contextHandler.Initialize(new IntPtr(0), dobj, 0);
            contextHandler.QueryContextMenu(0, 0, 0, 0, 0); // This fails, but  that's ok

            cmd        = new CMINVOKECOMMANDINFOEX();
            cmd.lpVerb = new IntPtr((int)ContextMenuVerbs.Import);
            cw         = new CommandWrapper(cmd);
            contextHandler.InvokeCommand(cw.Ptr);

            Marshal.ReleaseComObject(contextHandler);  // preempt GC for CCW

            // Go around one last time, reading and checking the imported values
            // We don't use the Code Pack because of it's boolean value bug
            errors = GetAndCheckValues(fileName2, state, false);

            state.RecordEntry(String.Format("{0} properties read back, {1} mismatches", savedProps.Count, errors));

            // Clean up files - checks if they have been released, too
            // Leave files around for analysis if there have been problems
            if (errors == 0)
            {
                File.Delete(fileName);
                File.Delete(fileName2);
                File.Delete(MetadataFileName(fileName2));
            }

            return(errors == 0);
        }
Ejemplo n.º 57
0
 public FilePropertyProvider(ShellObject shellObject)
 {
     _shellObject = shellObject;
     Items        = new ConcurrentDictionary <string, PropertyItem>();
 }
Ejemplo n.º 58
0
 private void BtnNavUp_Click(object sender, EventArgs e)
 {
     Browser.Navigate(ShellObject.FromParsingName(Directory.GetParent(txtNav.Text).FullName));
 }
Ejemplo n.º 59
0
        public void DoSearch(string SearchCriteria)
        {
            if (backgroundSearchThread != null)
                backgroundSearchThread.Abort();


            if (Explorer.NavigationLog.CurrentLocation.IsSearchFolder)
            {
                if (BeforeSearchFolder == null)
                {
                    BeforeSearchFolder = Explorer.NavigationLog.CurrentLocation;
                }
            }
            else
            {
                BeforeSearchFolder = Explorer.NavigationLog.CurrentLocation;
            }

            if (SearchCriteria != "")
            {

                backgroundSearchThread = new Thread(new ParameterizedThreadStart(DoSimpleSearch));
                backgroundSearchThread.IsBackground = true;
                // ApartmentState.STA is required for COM
                backgroundSearchThread.SetApartmentState(ApartmentState.STA);
                backgroundSearchThread.Start(SearchCriteria);

            }
        }
Ejemplo n.º 60
0
        /// <summary>
        /// Single instance callback handler.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="args">The <see cref="SingleInstanceApplication.InstanceCallbackEventArgs"/> instance containing the event data.</param>
        private void SingleInstanceCallback(object sender, InstanceCallbackEventArgs args)
        {
            string      StartUpLocation = KnownFolders.Libraries.ParsingName;
            RegistryKey rk  = Registry.CurrentUser;
            RegistryKey rks = rk.OpenSubKey(@"Software\BExplorer", false);

            StartUpLocation =
                rks.GetValue(@"StartUpLoc", KnownFolders.Libraries.ParsingName).ToString();



            if (args == null || Dispatcher == null)
            {
                return;
            }


            Action <bool> d = (bool x) =>
            {
                var win = MainWindow as MainWindow;
                if (win == null)
                {
                    return;
                }
                var hwnd = (HwndSource.FromVisual(win) as HwndSource).Handle;
                win.ApendArgs(args.CommandLineArgs);

                if (x)
                {
                    ShellObject sho = null;
                    if (args != null && args.CommandLineArgs != null)
                    {
                        if (args.CommandLineArgs.Length > 1 && args.CommandLineArgs[1] != null && args.CommandLineArgs[1] != "-minimized")
                        {
                            if (args.CommandLineArgs[1] != "t")
                            {
                                if (args.CommandLineArgs[1] == "nw")
                                {
                                    MainWindow g = new MainWindow();
                                    g.Show();
                                    return;
                                }
                                else
                                {
                                    win.Visibility = Visibility.Visible;
                                    if (win.WindowState == WindowState.Minimized)
                                    {
                                        WindowsAPI.ShowWindow(hwnd,
                                                              (int)WindowsAPI.ShowCommands.SW_RESTORE);
                                    }

                                    String cmd = args.CommandLineArgs[1];
                                    if (cmd.IndexOf("::") == 0)
                                    {
                                        sho = ShellObject.FromParsingName("shell:" + cmd);
                                    }
                                    else
                                    {
                                        sho = ShellObject.FromParsingName(args.CommandLineArgs[1].Replace("\"", ""));
                                    }
                                }
                            }
                            else
                            {
                                win.Visibility = Visibility.Visible;
                                if (win.WindowState == WindowState.Minimized)
                                {
                                    WindowsAPI.ShowWindow(hwnd,
                                                          (int)WindowsAPI.ShowCommands.SW_RESTORE);
                                }
                                sho = win.GetShellObjectFromLocation(StartUpLocation);
                            }
                        }
                        else
                        {
                            win.Visibility = Visibility.Visible;
                            if (win.WindowState == WindowState.Minimized)
                            {
                                WindowsAPI.ShowWindow(hwnd,
                                                      (int)WindowsAPI.ShowCommands.SW_RESTORE);
                            }
                            sho = win.GetShellObjectFromLocation(StartUpLocation);
                        }

                        if (!isStartMinimized || win.tabControl1.Items.Count == 0)
                        {
                            sho.Thumbnail.FormatOption = ShellThumbnailFormatOption.IconOnly;
                            sho.Thumbnail.CurrentSize  = new Size(16, 16);
                            ClosableTabItem newt = new ClosableTabItem();
                            newt.Header            = sho.GetDisplayName(DisplayNameType.Default);
                            newt.TabIcon           = sho.Thumbnail.BitmapSource;
                            newt.PreviewMouseMove += newt_PreviewMouseMove;
                            newt.TabSelected      += win.newt_TabSelected;
                            newt.Path              = sho;
                            win.CloneTab(newt);
                        }
                        else
                        {
                            int RestoreTabs = (int)rks.GetValue(@"IsRestoreTabs", 1);
                            if (RestoreTabs == 0)
                            {
                                win.tabControl1.Items.Clear();
                                sho.Thumbnail.FormatOption = ShellThumbnailFormatOption.IconOnly;
                                sho.Thumbnail.CurrentSize  = new Size(16, 16);
                                ClosableTabItem newt = new ClosableTabItem();
                                newt.Header            = sho.GetDisplayName(DisplayNameType.Default);
                                newt.TabIcon           = sho.Thumbnail.BitmapSource;
                                newt.PreviewMouseMove += newt_PreviewMouseMove;
                                newt.TabSelected      += win.newt_TabSelected;
                                newt.Path              = sho;
                                win.CloneTab(newt);
                            }
                            if (args.CommandLineArgs.Length > 1 && args.CommandLineArgs[1] != null)
                            {
                                String cmd = args.CommandLineArgs[1];
                                if (cmd.IndexOf("::") == 0)
                                {
                                    sho = ShellObject.FromParsingName("shell:" + cmd);
                                }
                                else
                                {
                                    sho = ShellObject.FromParsingName(args.CommandLineArgs[1].Replace("\"", ""));
                                }

                                sho.Thumbnail.FormatOption = ShellThumbnailFormatOption.IconOnly;
                                sho.Thumbnail.CurrentSize  = new Size(16, 16);
                                ClosableTabItem newt = new ClosableTabItem();
                                newt.Header            = sho.GetDisplayName(DisplayNameType.Default);
                                newt.TabIcon           = sho.Thumbnail.BitmapSource;
                                newt.PreviewMouseMove += newt_PreviewMouseMove;
                                newt.TabSelected      += win.newt_TabSelected;
                                newt.Path              = sho;
                                win.CloneTab(newt);
                            }
                        }

                        rks.Close();
                        rk.Close();

                        win.Activate();
                        win.Topmost = true;  // important
                        win.Topmost = false; // important
                        win.Focus();         // important
                    }
                }
            };

            Dispatcher.BeginInvoke(d, true);
        }