Ejemplo n.º 1
0
        /// <summary>
        /// Creates a ShellObject given a parsing name
        /// </summary>
        /// <param name="parsingName"></param>
        /// <returns>A newly constructed ShellObject object</returns>
        internal static ShellObject Create(string parsingName)
        {
            if (string.IsNullOrEmpty(parsingName))
            {
                throw new ArgumentNullException("parsingName");
            }

            // Create a native shellitem from our path
            IShellItem2 nativeShellItem;
            Guid        guid    = new Guid(ShellIIDGuid.IShellItem2);
            int         retCode = ShellNativeMethods.SHCreateItemFromParsingName(parsingName, IntPtr.Zero, ref guid, out nativeShellItem);

            if (!CoreErrorHelper.Succeeded(retCode))
            {
                throw new ShellException(LocalizedMessages.ShellObjectFactoryUnableToCreateItem, Marshal.GetExceptionForHR(retCode));
            }
            return(ShellObjectFactory.Create(nativeShellItem));
        }
Ejemplo n.º 2
0
        internal static IPropertyStore CreateDefaultPropertyStore(ShellObject shellObj)
        {
            IPropertyStore nativePropertyStore = null;

            Guid guid = new Guid(ShellIIDGuid.IPropertyStore);
            int  hr   = shellObj.NativeShellItem2.GetPropertyStore(
                ShellNativeMethods.GETPROPERTYSTOREFLAGS.GPS_BESTEFFORT,
                ref guid,
                out nativePropertyStore);

            // throw on failure
            if (nativePropertyStore == null || !CoreErrorHelper.Succeeded(hr))
            {
                Marshal.ThrowExceptionForHR(hr);
            }

            return(nativePropertyStore);
        }
Ejemplo n.º 3
0
        public static void SetWindowProperty(IntPtr hwnd, PropertyKey propkey, string value)
        {
            // Get the IPropertyStore for the given window handle
            IPropertyStore propStore = GetWindowPropertyStore(hwnd);

            // Set the value
            using (PropVariant pv = new PropVariant(value)) {
                HResult result = propStore.SetValue(ref propkey, pv);
                if (!CoreErrorHelper.Succeeded(result))
                {
                    throw new ShellException(result);
                }
            }


            // Dispose the IPropertyStore and PropVariant
            Marshal.ReleaseComObject(propStore);
        }
        /// <summary>
        /// Returns a formatted, Unicode string representation of a property value.
        /// </summary>
        /// <param name="format">One or more of the PropertyDescriptionFormat flags 
        /// that indicate the desired format.</param>
        /// <returns>The formatted value as a string, or null if this property 
        /// cannot be formatted for display.</returns>
        public string FormatForDisplay(PropertyDescriptionFormatOptions format)
        {
            if (Description == null || Description.NativePropertyDescription == null)

                // We cannot do anything without a property description
                return null;

            IPropertyStore store = ShellPropertyCollection.CreateDefaultPropertyStore(ParentShellObject);

#if CS7

            using (var propVar = new PropVariant())

            {

#else

            using var propVar = new PropVariant();

#endif

            _ = store.GetValue(ref propertyKey, propVar);

            // Release the Propertystore
            _ = Marshal.ReleaseComObject(store);
            store = null;

            HResult hr = Description.NativePropertyDescription.FormatForDisplay(propVar, ref format, out string formattedString);

            // Sometimes, the value cannot be displayed properly, such as for blobs
            // or if we get argument exception
            if (!CoreErrorHelper.Succeeded(hr))

                throw new ShellException(hr);

            return formattedString;

#if CS7

            }

#endif

        }
        // todo: to encapsulate

        /// <summary>
        /// Declares a set of properties and values to be set on an item or items.
        /// </summary>
        /// <param name="pproparray">An <see cref="IPropertyChangeArray"/>, which accesses a collection of <see cref="IPropertyChange"/> objects that specify the properties to be set and their new values.</param>
        /// <remarks>This method does not set the new property values, it merely declares them. To set property values on an item or a group of items, you must make at least the sequence of calls detailed here:
        /// <ol><li>Call <see cref="SetProperties"/> to declare the specific properties to be set and their new values.</li>
        /// <li>Call <see cref="ApplyPropertiesToItem(ShellObject)"/> or <see cref="ApplyPropertiesToItem(IShellItem)"/> to declare the item or items whose properties are to be set.</li>
        /// <li>Call <see cref="PerformOperations"/> to apply the properties to the item or items.</li></ol></remarks>
        /// <exception cref="ArgumentNullException">Exception thrown when a parameter is null.</exception>
        /// <exception cref="ObjectDisposedException">Exception thrown when this object is disposed.</exception>
        /// <exception cref="Win32Exception">Exception thrown when this method fails because of an error in the Win32 COM API implementation.</exception>
        public void SetProperties(IPropertyChangeArray pproparray)
        {
            if (pproparray == null)
            {
                throw new ArgumentNullException(nameof(pproparray));
            }

            if (disposed)
            {
                throw new ObjectDisposedException(nameof(FileOperation));
            }

            HResult hr = fileOperation.SetProperties(pproparray);

            if (!CoreErrorHelper.Succeeded(hr))
            {
                Marshal.ThrowExceptionForHR((int)hr);
            }
        }
        private void AddButtons(TaskbarWindow taskbarWindow)
        {
            // Add the buttons
            // Get the array of thumbnail buttons in native format
            THUMBBUTTON[] nativeButtons = (from thumbButton in taskbarWindow.ThumbnailButtons
                                           select thumbButton.Win32ThumbButton).ToArray();

            // Add the buttons on the taskbar
            HRESULT hr = TaskbarManager.Instance.TaskbarList.ThumbBarAddButtons(taskbarWindow.WindowToTellTaskbarAbout, (uint)taskbarWindow.ThumbnailButtons.Length, nativeButtons);

            if (!CoreErrorHelper.Succeeded((int)hr))
            {
                Marshal.ThrowExceptionForHR((int)hr);
            }

            // Set the window handle on the buttons (for future updates)
            buttonsAdded = true;
            Array.ForEach(taskbarWindow.ThumbnailButtons, new Action <ThumbnailToolbarButton>(UpdateHandle));
        }
        /// <summary>
        /// Gets the localized display string that describes the current sort order.
        /// </summary>
        /// <param name="descending">Indicates the sort order should
        /// reference the string "Z on top"; otherwise, the sort order should reference the string "A on top".</param>
        /// <returns>The sort description for this property.</returns>
        /// <remarks>The string retrieved by this method is determined by flags set in the
        /// <c>sortDescription</c> attribute of the <c>labelInfo</c> element in the property's .propdesc file.</remarks>
        public string GetSortDescriptionLabel(bool descending)
        {
            IntPtr ptr   = IntPtr.Zero;
            string label = String.Empty;

            if (NativePropertyDescription != null)
            {
                HRESULT hr = NativePropertyDescription.GetSortDescriptionLabel(descending, out ptr);

                if (CoreErrorHelper.Succeeded((int)hr) && ptr != IntPtr.Zero)
                {
                    label = Marshal.PtrToStringUni(ptr);
                    // Free the string
                    Marshal.FreeCoTaskMem(ptr);
                }
            }

            return(label);
        }
Ejemplo n.º 8
0
        private void StorePropVariantValue(PropVariant propVar)
        {
            Guid           guid = new Guid(ShellIIDGuid.IPropertyStore);
            IPropertyStore writablePropStore = null;

            try {
                int hr = ParentShellObject.NativeShellItem2.GetPropertyStore(
                    ShellNativeMethods.GetPropertyStoreOptions.ReadWrite,
                    ref guid,
                    out writablePropStore);

                if (!CoreErrorHelper.Succeeded(hr))
                {
                    throw new PropertySystemException(LocalizedMessages.ShellPropertyUnableToGetWritableProperty,
                                                      Marshal.GetExceptionForHR(hr));
                }

                HResult result = writablePropStore.SetValue(ref propertyKey, propVar);

                if (!AllowSetTruncatedValue && (int)result == ShellNativeMethods.InPlaceStringTruncated)
                {
                    throw new ArgumentOutOfRangeException("propVar", LocalizedMessages.ShellPropertyValueTruncated);
                }

                if (!CoreErrorHelper.Succeeded(result))
                {
                    throw new PropertySystemException(LocalizedMessages.ShellPropertySetValue, Marshal.GetExceptionForHR((int)result));
                }

                writablePropStore.Commit();
            } catch (InvalidComObjectException e) {
                throw new PropertySystemException(LocalizedMessages.ShellPropertyUnableToGetWritableProperty, e);
            } catch (InvalidCastException) {
                throw new PropertySystemException(LocalizedMessages.ShellPropertyUnableToGetWritableProperty);
            } finally {
                if (writablePropStore != null)
                {
                    Marshal.ReleaseComObject(writablePropStore);
                    writablePropStore = null;
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Constructs a new Shell object from IDList pointer
        /// </summary>
        /// <param name="idListPtr"></param>
        /// <returns></returns>
        internal static ShellObject Create(IntPtr idListPtr)
        {
            // Throw exception if not running on Win7 or newer.
            CoreHelpers.ThrowIfNotVista();

            Guid        guid = new Guid(ShellIIDGuid.IShellItem2);
            IShellItem2 nativeShellItem;
            int         retCode = ShellNativeMethods.SHCreateItemFromIDList(idListPtr, ref guid, out nativeShellItem);

            if (CoreErrorHelper.Succeeded(retCode))
            {
                return(ShellObjectFactory.Create(nativeShellItem));
            }
            else
            {
                // Since this is an internal method, return null instead of throwing an exception.
                // Let the caller know we weren't able to create a valid ShellObject with the given PIDL
                return(null);
            }
        }
        private static void AddButtons(TaskbarWindow taskbarWindow)
        {
            // Add the buttons
            // Get the array of thumbnail buttons in native format
            ThumbButton[] nativeButtons = (from thumbButton in taskbarWindow.ThumbnailButtons
                                           select thumbButton.Win32ThumbButton).ToArray();

            // Add the buttons on the taskbar
            HResult hr = TaskbarList.Instance.ThumbBarAddButtons(taskbarWindow.WindowToTellTaskbarAbout, (uint)taskbarWindow.ThumbnailButtons.Length, nativeButtons);

            if (!CoreErrorHelper.Succeeded(hr))

                throw new ShellException(hr);

            _buttonsAdded = true;

            foreach (ThumbnailToolBarButton button in taskbarWindow.ThumbnailButtons)

                button.AddedToTaskbar = _buttonsAdded;
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Constructs a new Shell object from IDList pointer
        /// </summary>
        /// <param name="idListPtr"></param>
        /// <param name="parent"></param>
        /// <returns></returns>
        internal static ShellObject Create(IntPtr idListPtr, ShellContainer parent)
        {
            IShellItem nativeShellItem;

            int retCode = ShellNativeMethods.SHCreateShellItem(
                IntPtr.Zero,
                parent.NativeShellFolder,
                idListPtr, out nativeShellItem);

            if (CoreErrorHelper.Succeeded(retCode))
            {
                return(ShellObjectFactory.Create(nativeShellItem));
            }
            else
            {
                // Since this is an internal method, return null instead of throwing an exception.
                // Let the caller know we weren't able to create a valid ShellObject with the given PIDL
                return(null);
            }
        }
        public bool GetAnyOperationsAborted()
        {
            if (disposed)
            {
                throw new ObjectDisposedException(nameof(FileOperation));
            }

            HResult hr = fileOperation.GetAnyOperationsAborted(out bool anyOperationsAborted);

            if (CoreErrorHelper.Succeeded(hr))
            {
                return(anyOperationsAborted);
            }

            else
            {
                Marshal.ThrowExceptionForHR((int)hr);
            }

            return(false);
        }
Ejemplo n.º 13
0
        internal ShellFolderItems(ShellContainer nativeShellFolder)
        {
            this.nativeShellFolder = nativeShellFolder;

            HResult hr = nativeShellFolder.NativeShellFolder.EnumObjects(
                IntPtr.Zero,
                ShellNativeMethods.ShellFolderEnumerationOptions.Folders | ShellNativeMethods.ShellFolderEnumerationOptions.NonFolders,
                out this.nativeEnumIdList);

            if (!CoreErrorHelper.Succeeded(hr))
            {
                if (hr == HResult.Canceled)
                {
                    throw new System.IO.FileNotFoundException();
                }
                else
                {
                    throw new ShellException(hr);
                }
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Registers an application for recovery by Application Restart and Recovery.
        /// </summary>
        /// <param name="settings">An object that specifies
        /// the callback method, an optional parameter to pass to the callback
        /// method and a time interval.</param>
        /// <exception cref="System.ArgumentException">
        /// The registration failed due to an invalid parameter.
        /// </exception>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// The registration failed.</exception>
        /// <remarks>The time interval is the period of time within 
        /// which the recovery callback method 
        /// calls the <see cref="ApplicationRecoveryInProgress"/> method to indicate
        /// that it is still performing recovery work.</remarks>        
        public static void RegisterForApplicationRecovery(RecoverySettings settings)
        {           
            CoreHelpers.ThrowIfNotVista();

            if (settings == null) { throw new ArgumentNullException("settings"); }

            GCHandle handle = GCHandle.Alloc(settings.RecoveryData);

            HResult hr = AppRestartRecoveryNativeMethods.RegisterApplicationRecoveryCallback(
                AppRestartRecoveryNativeMethods.InternalCallback, (IntPtr)handle, settings.PingInterval, (uint)0);

            if (!CoreErrorHelper.Succeeded(hr))
            {
                if (hr == HResult.InvalidArguments)
                {
                    throw new ArgumentException(LocalizedMessages.ApplicationRecoveryBadParameters, "settings");
                }

                throw new ApplicationRecoveryException(LocalizedMessages.ApplicationRecoveryFailedToRegister);
            }
        }
Ejemplo n.º 15
0
        private static SearchCondition CreateLeafCondition(string propertyName, PropVariant propVar, string valueType, SearchConditionOperation operation)
        {
            IConditionFactory nativeConditionFactory = null;
            SearchCondition   condition = null;

            try
            {
                // Same as the native "IConditionFactory:MakeLeaf" method
                nativeConditionFactory = (IConditionFactory) new ConditionFactoryCoClass();

                ICondition nativeCondition = null;

                if (string.IsNullOrEmpty(propertyName) || propertyName.ToLower() == "system.null")
                {
                    propertyName = null;
                }

                HRESULT hr = HRESULT.E_FAIL;

                hr = nativeConditionFactory.MakeLeaf(propertyName, operation, valueType,
                                                     ref propVar, null, null, null, false, out nativeCondition);

                if (!CoreErrorHelper.Succeeded((int)hr))
                {
                    Marshal.ThrowExceptionForHR((int)hr);
                }

                // Create our search condition and set the various properties.
                condition = new SearchCondition(nativeCondition);
            }
            finally
            {
                if (nativeConditionFactory != null)
                {
                    Marshal.ReleaseComObject(nativeConditionFactory);
                }
            }

            return(condition);
        }
        private static SearchCondition CreateLeafCondition(string propertyName, PropVariant propVar, string valueType, SearchConditionOperation operation)
        {
            IConditionFactory nativeConditionFactory = null;
            SearchCondition   condition = null;

            try
            {
                // Same as the native "IConditionFactory:MakeLeaf" method
                nativeConditionFactory = (IConditionFactory) new ConditionFactoryCoClass();

                ICondition nativeCondition = null;

                if (string.IsNullOrEmpty(propertyName) || propertyName.ToUpperInvariant() == "SYSTEM.NULL")
                {
                    propertyName = null;
                }

                HResult hr = HResult.Fail;

                hr = nativeConditionFactory.MakeLeaf(propertyName, operation, valueType,
                                                     propVar, null, null, null, false, out nativeCondition);

                if (!CoreErrorHelper.Succeeded(hr))
                {
                    throw new ShellException(hr);
                }

                // Create our search condition and set the various properties.
                condition = new SearchCondition(nativeCondition);
            }
            finally
            {
                if (nativeConditionFactory != null)
                {
                    Marshal.ReleaseComObject(nativeConditionFactory);
                }
            }

            return(condition);
        }
Ejemplo n.º 17
0
        internal ShellFolderItems(ShellContainer nativeShellFolder)
        {
            this.nativeShellFolder = nativeShellFolder;

            HRESULT hr = nativeShellFolder.NativeShellFolder.EnumObjects(
                IntPtr.Zero,
                ShellNativeMethods.SHCONT.SHCONTF_FOLDERS | ShellNativeMethods.SHCONT.SHCONTF_NONFOLDERS,
                out nativeEnumIdList);


            if (!CoreErrorHelper.Succeeded((int)hr))
            {
                if (hr == HRESULT.E_ERROR_CANCELLED)
                {
                    throw new System.IO.FileNotFoundException( );
                }
                else
                {
                    Marshal.ThrowExceptionForHR((int)hr);
                }
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Load the library using a number of options
        /// </summary>
        /// <param name="libraryName">The name of the library</param>
        /// <param name="isReadOnly">If <B>true</B>, loads the library in read-only mode.</param>
        /// <returns>A ShellLibrary Object</returns>
        public static ShellLibrary Load(string libraryName, bool isReadOnly)
        {
            CoreHelpers.ThrowIfNotWin7();

            IKnownFolder kf = KnownFolders.Libraries;
            string       librariesFolderPath = (kf != null) ? kf.Path : string.Empty;

            Guid       guid = new Guid(ShellIIDGuid.IShellItem);
            IShellItem nativeShellItem;
            string     shellItemPath = System.IO.Path.Combine(librariesFolderPath, libraryName + FileExtension);
            int        hr            = ShellNativeMethods.SHCreateItemFromParsingName(shellItemPath, IntPtr.Zero, ref guid, out nativeShellItem);

            if (!CoreErrorHelper.Succeeded(hr))
            {
                throw new ShellException(hr);
            }

            INativeShellLibrary nativeShellLibrary = (INativeShellLibrary) new ShellLibraryCoClass();
            AccessModes         flags = isReadOnly ?
                                        AccessModes.Read :
                                        AccessModes.ReadWrite;

            nativeShellLibrary.LoadLibraryFromItem(nativeShellItem, flags);

            ShellLibrary library = new ShellLibrary(nativeShellLibrary);

            try
            {
                library.nativeShellItem = (IShellItem2)nativeShellItem;
                library.Name            = libraryName;

                return(library);
            }
            catch
            {
                library.Dispose();
                throw;
            }
        }
Ejemplo n.º 19
0
        internal ShellPropertyWriter(ShellObject parent)
        {
            this.ParentShellObject = parent;

            // Open the property store for this shell object...
            Guid guid = new Guid(ShellIIDGuid.IPropertyStore);

            try
            {
                int hr = this.ParentShellObject.NativeShellItem2.GetPropertyStore(
                    ShellNativeMethods.GetPropertyStoreOptions.ReadWrite,
                    ref guid,
                    out this.writablePropStore);

                if (!CoreErrorHelper.Succeeded(hr))
                {
                    throw new PropertySystemException(LocalizedMessages.ShellPropertyUnableToGetWritableProperty,
                                                      Marshal.GetExceptionForHR(hr));
                }
                else
                {
                    // If we succeed in creating a valid property store for this ShellObject,
                    // then set it on the parent shell object for others to use.
                    // Once this writer is closed/commited, we will set the
                    if (this.ParentShellObject.NativePropertyStore == null)
                    {
                        this.ParentShellObject.NativePropertyStore = this.writablePropStore;
                    }
                }
            }
            catch (InvalidComObjectException e)
            {
                throw new PropertySystemException(LocalizedMessages.ShellPropertyUnableToGetWritableProperty, e);
            }
            catch (InvalidCastException)
            {
                throw new PropertySystemException(LocalizedMessages.ShellPropertyUnableToGetWritableProperty);
            }
        }
Ejemplo n.º 20
0
        internal ShellPropertyWriter(ShellObject parent)
        {
            ParentShellObject = parent;

            // Open the property store for this shell object...
            Guid guid = new Guid(ShellIIDGuid.IPropertyStore);

            try
            {
                int hr = ParentShellObject.NativeShellItem2.GetPropertyStore(
                    ShellNativeMethods.GETPROPERTYSTOREFLAGS.GPS_READWRITE,
                    ref guid,
                    out writablePropStore);

                if (!CoreErrorHelper.Succeeded(hr))
                {
                    throw new ExternalException("Unable to get writable property store for this property.",
                                                Marshal.GetExceptionForHR(hr));
                }
                else
                {
                    // If we succeed in creating a valid property store for this ShellObject,
                    // then set it on the parent shell object for others to use.
                    // Once this writer is closed/commited, we will set the
                    if (ParentShellObject.NativePropertyStore == null)
                    {
                        ParentShellObject.NativePropertyStore = writablePropStore;
                    }
                }
            }
            catch (InvalidComObjectException e)
            {
                throw new ExternalException("Unable to get writable property store for this property.", e);
            }
            catch (InvalidCastException)
            {
                throw new ExternalException("Unable to get writable property store for this property.");
            }
        }
Ejemplo n.º 21
0
        private void AppendTaskList()
        {
            if (userTasks == null || userTasks.Count == 0)
            {
                return;
            }

            IObjectCollection taskContent =
                (IObjectCollection) new CEnumerableObjectCollection();

            // Add each task's shell representation to the object array
            foreach (IJumpListTask task in userTasks)
            {
                if (task is JumpListLink)
                {
                    taskContent.AddObject(((JumpListLink)task).NativeShellLink);
                }
                else if (task is JumpListSeparator)
                {
                    taskContent.AddObject(((JumpListSeparator)task).NativeShellLink);
                }
            }

            // Add tasks to the taskbar
            HRESULT hr = customDestinationList.AddUserTasks((IObjectArray)taskContent);

            if (!CoreErrorHelper.Succeeded((int)hr))
            {
                if ((uint)hr == 0x80040F03)
                {
                    throw new InvalidOperationException("The file type is not registered with this application.");
                }
                else
                {
                    Marshal.ThrowExceptionForHR((int)hr);
                }
            }
        }
        /// <summary>
        /// Sets parameters for the current operation.
        /// </summary>
        /// <param name="dwOperationFlags">Flags that control the file operation. FOF flags are defined in Shellapi.h and FOFX flags are defined in Shobjidl.h. Note : If this method is not called, the default value used by the operation is <see cref=" ShellOperationFlags.FOF_ALLOWUNDO"/> | <see cref="ShellOperationFlags.FOF_NOCONFIRMMKDIR"/>.</param>
        /// <remarks>Set these flags before you call <see cref="PerformOperations"/> to define the parameters for whatever operations are being performed, such as copy, delete, or rename.</remarks>
        /// <exception cref="ObjectDisposedException">Exception thrown when this object is disposed.</exception>
        /// <exception cref="PlatformNotSupportedException">Exception thrown when a requested flag is not supported by the current platform.</exception>
        /// <exception cref="Win32Exception">Exception thrown when this method fails because of an error in the Win32 COM API implementation.</exception>
        public void SetOperationFlags(ShellOperationFlags dwOperationFlags)
        {
            if (disposed)
            {
                throw new ObjectDisposedException(nameof(FileOperation));
            }

            switch (dwOperationFlags)

            {
            case ShellOperationFlags.AddUndoRecord:
            case ShellOperationFlags.RecycleOnDelete:

                CoreHelpers.ThrowIfNotWin8();

                break;

            case ShellOperationFlags.CopyAsDownload:
            case ShellOperationFlags.DoNotDisplayLocations:

                CoreHelpers.ThrowIfNotWin7();

                break;

            case ShellOperationFlags.RequireElevation:

                CoreHelpers.ThrowIfNotVista();

                break;
            }

            HResult hr = fileOperation.SetOperationFlags(dwOperationFlags);

            if (!CoreErrorHelper.Succeeded(hr))
            {
                Marshal.ThrowExceptionForHR((int)hr);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Given a native KnownFolder (IKnownFolderNative), create the right type of
        /// IKnownFolder object (FileSystemKnownFolder or NonFileSystemKnownFolder)
        /// </summary>
        /// <param name="knownFolderNative">Native Known Folder</param>
        /// <returns></returns>
        private static IKnownFolder GetKnownFolder(IKnownFolderNative knownFolderNative)
        {
            Debug.Assert(knownFolderNative != null, "Native IKnownFolder should not be null.");

            // Get the native IShellItem2 from the native IKnownFolder
            IShellItem2 shellItem;
            Guid        guid = new Guid(ShellIIDGuid.IShellItem2);
            HRESULT     hr   = knownFolderNative.GetShellItem(0, ref guid, out shellItem);

            if (!CoreErrorHelper.Succeeded((int)hr))
            {
                return(null);
            }

            bool isFileSystem = false;

            // If we have a valid IShellItem, try to get the FileSystem attribute.
            if (shellItem != null)
            {
                ShellNativeMethods.SFGAO sfgao;
                shellItem.GetAttributes(ShellNativeMethods.SFGAO.SFGAO_FILESYSTEM, out sfgao);

                // Is this item a FileSystem item?
                isFileSystem = (sfgao & ShellNativeMethods.SFGAO.SFGAO_FILESYSTEM) != 0;
            }

            // If it's FileSystem, create a FileSystemKnownFolder, else NonFileSystemKnownFolder
            if (isFileSystem)
            {
                FileSystemKnownFolder kf = new FileSystemKnownFolder(knownFolderNative);
                return(kf);
            }
            else
            {
                NonFileSystemKnownFolder kf = new NonFileSystemKnownFolder(knownFolderNative);
                return(kf);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Creates a condition node that is a logical conjunction ("AND") or disjunction ("OR")
        /// of a collection of subconditions.
        /// </summary>
        /// <param name="conditionType">The SearchConditionType of the condition node.
        /// Must be either AndCondition or OrCondition.</param>
        /// <param name="simplify">TRUE to logically simplify the result, if possible;
        /// then the result will not necessarily to be of the specified kind. FALSE if the result should
        /// have exactly the prescribed structure. An application that plans to execute a query based on the
        /// condition tree would typically benefit from setting this parameter to TRUE. </param>
        /// <param name="conditionNodes">Array of subconditions</param>
        /// <returns>New SearchCondition based on the operation</returns>
        public static SearchCondition CreateAndOrCondition(SearchConditionType conditionType, bool simplify, params SearchCondition[] conditionNodes)
        {
            // Same as the native "IConditionFactory:MakeAndOr" method
            var        nativeConditionFactory = (IConditionFactory) new ConditionFactoryCoClass();
            ICondition result = null;

            try
            {
                //
                var conditionList = new List <ICondition>();

                if (conditionNodes != null)
                {
                    foreach (SearchCondition c in conditionNodes)
                    {
                        conditionList.Add(c.NativeSearchCondition);
                    }
                }

                IEnumUnknown subConditions = new EnumUnknownClass(conditionList.ToArray());

                HResult hr = nativeConditionFactory.MakeAndOr(conditionType, subConditions, simplify, out result);

                if (!CoreErrorHelper.Succeeded(hr))
                {
                    throw new ShellException(hr);
                }
            }
            finally
            {
                if (nativeConditionFactory != null)
                {
                    _ = Marshal.ReleaseComObject(nativeConditionFactory);
                }
            }

            return(new SearchCondition(result));
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Creates a list of stack keys, as specified. If this method is not called,
        /// by default the folder will not be stacked.
        /// </summary>
        /// <param name="canonicalNames">Array of canonical names for properties on which the folder is stacked.</param>
        /// <exception cref="System.ArgumentException">If one of the given canonical names is invalid.</exception>
        public void SetStacks(params string[] canonicalNames)
        {
            List <PropertyKey> propertyKeyList = new List <PropertyKey>();

            foreach (string prop in canonicalNames)
            {
                // Get the PropertyKey using the canonicalName passed in
                PropertyKey propKey;
                int         result = PropertySystemNativeMethods.PSGetPropertyKeyFromName(prop, out propKey);

                if (!CoreErrorHelper.Succeeded(result))
                {
                    throw new ArgumentException("The given CanonicalName is not valid.", "canonicalNames", Marshal.GetExceptionForHR(result));
                }

                propertyKeyList.Add(propKey);
            }

            if (propertyKeyList.Count > 0)
            {
                SetStacks(propertyKeyList.ToArray());
            }
        }
Ejemplo n.º 26
0
        private void AppendTaskList()
        {
            if (userTasks == null || userTasks.Count == 0)
            {
                return;
            }

            IObjectCollection taskContent =
                (IObjectCollection) new CEnumerableObjectCollection();

            // Add each task's shell representation to the object array
            foreach (JumpListTask task in userTasks)
            {
                JumpListSeparator seperator;
                JumpListLink      link = task as JumpListLink;
                if (link != null)
                {
                    taskContent.AddObject(link.NativeShellLink);
                }
                else if ((seperator = task as JumpListSeparator) != null)
                {
                    taskContent.AddObject(seperator.NativeShellLink);
                }
            }

            // Add tasks to the taskbar
            HResult hr = customDestinationList.AddUserTasks((IObjectArray)taskContent);

            if (!CoreErrorHelper.Succeeded(hr))
            {
                if ((uint)hr == 0x80040F03)
                {
                    throw new InvalidOperationException(LocalizedMessages.JumpListFileTypeNotRegistered);
                }
                throw new ShellException(hr);
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Retrieves an array of the sub-conditions.
        /// </summary>
        public IEnumerable <SearchCondition> GetSubConditions()
        {
            // Our list that we'll return
            List <SearchCondition> subConditionsList = new List <SearchCondition>();

            // Get the sub-conditions from the native API
            object subConditionObj;
            Guid   guid = new Guid(ShellIIDGuid.IEnumUnknown);

            HResult hr = NativeSearchCondition.GetSubConditions(ref guid, out subConditionObj);

            if (!CoreErrorHelper.Succeeded(hr))
            {
                throw new ShellException(hr);
            }

            // Convert each ICondition to SearchCondition
            if (subConditionObj != null)
            {
                IEnumUnknown enumUnknown = subConditionObj as IEnumUnknown;

                IntPtr buffer  = IntPtr.Zero;
                uint   fetched = 0;

                while (hr == HResult.Ok)
                {
                    hr = enumUnknown.Next(1, ref buffer, ref fetched);

                    if (hr == HResult.Ok && fetched == 1)
                    {
                        subConditionsList.Add(new SearchCondition((ICondition)Marshal.GetObjectForIUnknown(buffer)));
                    }
                }
            }

            return(subConditionsList);
        }
Ejemplo n.º 28
0
        private static void ShowManageLibraryUI(ShellLibrary shellLibrary, IntPtr windowHandle, string title, string instruction, bool allowAllLocations)
        {
            int hr = 0;

            Thread staWorker = new Thread(() => {
                hr = ShellNativeMethods.SHShowManageLibraryUI(
                    shellLibrary.NativeShellItem,
                    windowHandle,
                    title,
                    instruction,
                    allowAllLocations ?
                    ShellNativeMethods.LibraryManageDialogOptions.NonIndexableLocationWarning :
                    ShellNativeMethods.LibraryManageDialogOptions.Default);
            });

            staWorker.SetApartmentState(ApartmentState.STA);
            staWorker.Start();
            staWorker.Join();

            if (!CoreErrorHelper.Succeeded(hr))
            {
                throw new ShellException(hr);
            }
        }
Ejemplo n.º 29
0
        internal SearchCondition(ICondition nativeSearchCondition)
        {
            if (nativeSearchCondition == null)
            {
                throw new ArgumentNullException("nativeSearchCondition");
            }

            NativeSearchCondition = nativeSearchCondition;

            HRESULT hr = NativeSearchCondition.GetConditionType(out conditionType);

            if (!CoreErrorHelper.Succeeded((int)hr))
            {
                Marshal.ThrowExceptionForHR((int)hr);
            }

            if (ConditionType == SearchConditionType.Leaf)
            {
                PropVariant propVar;
                hr = NativeSearchCondition.GetComparisonInfo(out canonicalName, out conditionOperation, out propVar);

                if (!CoreErrorHelper.Succeeded((int)hr))
                {
                    Marshal.ThrowExceptionForHR((int)hr);
                }

                try
                {
                    propertyValue = propVar.Value.ToString();
                }
                finally
                {
                    propVar.Clear();
                }
            }
        }
        /// <summary>
        /// Parses an input string that contains Structured Query keywords (using Advanced Query Syntax
        /// or Natural Query Syntax) and produces a SearchCondition object.
        /// </summary>
        /// <param name="query">The query to be parsed</param>
        /// <param name="cultureInfo">The culture used to select the localized language for keywords.</param>
        /// <returns>Search condition resulting from the query</returns>
        /// <remarks>For more information on structured query syntax, visit http://msdn.microsoft.com/en-us/library/bb233500.aspx and
        /// http://www.microsoft.com/windows/products/winfamily/desktopsearch/technicalresources/advquery.mspx</remarks>
        public static SearchCondition ParseStructuredQuery(string query, CultureInfo cultureInfo)
        {
            if (string.IsNullOrEmpty(query))
            {
                throw new ArgumentNullException(nameof(query));
            }

            IQueryParserManager nativeQueryParserManager = (IQueryParserManager) new QueryParserManagerCoClass();
            IQueryParser        queryParser   = null;
            IQuerySolution      querySolution = null;
            ICondition          result        = null;

            IEntity         mainType        = null;
            SearchCondition searchCondition = null;

            try
            {
                // First, try to create a new IQueryParser using IQueryParserManager
                Guid    guid = new Guid(ShellIIDGuid.IQueryParser);
                HResult hr   = nativeQueryParserManager.CreateLoadedParser(
                    "SystemIndex",
                    cultureInfo == null ? (ushort)0 : (ushort)cultureInfo.LCID,
                    ref guid,
                    out queryParser);

                if (!CoreErrorHelper.Succeeded(hr))
                {
                    throw new ShellException(hr);
                }

                if (queryParser != null)
                {
                    // If user specified natural query, set the option on the query parser
                    using (PropVariant optionValue = new PropVariant(true))
                    {
                        hr = queryParser.SetOption(StructuredQuerySingleOption.NaturalSyntax, optionValue);
                    }

                    if (!CoreErrorHelper.Succeeded(hr))
                    {
                        throw new ShellException(hr);
                    }

                    // Next, try to parse the query.
                    // Result would be IQuerySolution that we can use for getting the ICondition and other
                    // details about the parsed query.
                    hr = queryParser.Parse(query, null, out querySolution);

                    if (!CoreErrorHelper.Succeeded(hr))
                    {
                        throw new ShellException(hr);
                    }

                    if (querySolution != null)
                    {
                        // Lastly, try to get the ICondition from this parsed query
                        hr = querySolution.GetQuery(out result, out mainType);

                        if (!CoreErrorHelper.Succeeded(hr))
                        {
                            throw new ShellException(hr);
                        }
                    }
                }

                searchCondition = new SearchCondition(result);
                return(searchCondition);
            }
            catch
            {
                if (searchCondition != null)
                {
                    searchCondition.Dispose();
                }

                throw;
            }
            finally
            {
                if (nativeQueryParserManager != null)
                {
                    Marshal.ReleaseComObject(nativeQueryParserManager);
                }

                if (queryParser != null)
                {
                    Marshal.ReleaseComObject(queryParser);
                }

                if (querySolution != null)
                {
                    Marshal.ReleaseComObject(querySolution);
                }

                if (mainType != null)
                {
                    Marshal.ReleaseComObject(mainType);
                }
            }
        }