예제 #1
0
        /// <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(PropertyDescriptionFormat format)
        {
            string      formattedString;
            PropVariant propVar;

            if (Description == null || Description.NativePropertyDescription == null)
            {
                // We cannot do anything without a property description
                return(null);
            }

            IPropertyStore store = ShellPropertyCollection.CreateDefaultPropertyStore(ParentShellObject);

            store.GetValue(ref propertyKey, out propVar);

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

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

            // Sometimes, the value cannot be displayed properly, such as for blobs
            // or if we get argument exception
            if (!CoreErrorHelper.Succeeded((int)hr))
            {
                throw Marshal.GetExceptionForHR((int)hr);
            }
            else
            {
                return(formattedString);
            }
        }
예제 #2
0
        /// <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>
        /// <param name="formattedString">The formatted value as a string, or null if this property
        /// cannot be formatted for display.</param>
        /// <returns>True if the method successfully locates the formatted string; otherwise
        /// False.</returns>
        public bool TryFormatForDisplay(PropertyDescriptionFormatOptions format, out string formattedString)
        {
            if (Description == null || Description.NativePropertyDescription == null)
            {
                // We cannot do anything without a property description
                formattedString = null;
                return(false);
            }

            IPropertyStore store = ShellPropertyCollection.CreateDefaultPropertyStore(ParentShellObject);

            using (PropVariant propVar = new PropVariant())
            {
                store.GetValue(ref propertyKey, propVar);

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

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

                // Sometimes, the value cannot be displayed properly, such as for blobs
                // or if we get argument exception
                if (!CoreErrorHelper.Succeeded(hr))
                {
                    formattedString = null;
                    return(false);
                }
                return(true);
            }
        }
예제 #3
0
        private void GetImageReference()
        {
            IPropertyStore store = ShellPropertyCollection.CreateDefaultPropertyStore(this.ParentShellObject);

            using (PropVariant propVar = new PropVariant())
            {
                store.GetValue(ref this.propertyKey, propVar);

                Marshal.ReleaseComObject(store);
                store = null;

                string refPath;
                ((IPropertyDescription2)this.Description.NativePropertyDescription).GetImageReferenceForValue(
                    propVar, out refPath);

                if (refPath == null)
                {
                    return;
                }

                int index = ShellNativeMethods.PathParseIconLocation(ref refPath);
                if (refPath != null)
                {
                    this.imageReferencePath      = refPath;
                    this.imageReferenceIconIndex = index;
                }
            }
        }
예제 #4
0
        //Get the current default audio device
        public static AudioDeviceSummary GetDefaultDevice()
        {
            try
            {
                IMMDeviceEnumerator deviceEnumerator = (IMMDeviceEnumerator) new MMDeviceEnumerator();
                IMMDevice.IMMDevice deviceItem       = deviceEnumerator.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

                //Get the audio device id
                string deviceId = deviceItem.GetId();

                //Get the audio device name
                PropertyVariant propertyVariant = new PropertyVariant();
                IPropertyStore  propertyStore   = deviceItem.OpenPropertyStore(STGM.STGM_READ);
                propertyStore.GetValue(ref PKEY_Device_FriendlyName, out propertyVariant);
                string deviceName = Marshal.PtrToStringUni(propertyVariant.pwszVal);

                return(new AudioDeviceSummary()
                {
                    Identifier = deviceId, Name = deviceName
                });
            }
            catch
            {
                Debug.WriteLine("Failed to get the default audio device.");
                return(null);
            }
        }
예제 #5
0
        // T7E: Gets application ID for window
        public string GetApplicationIdForWindow(IntPtr windowHandle)
        {
            IPropertyStore propertyStore = TaskbarNativeMethods.GetWindowPropertyStore(windowHandle);

            PropVariant pv       = new PropVariant();
            PropertyKey AppIdKey = new PropertyKey(new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 5);

            propertyStore.GetValue(ref AppIdKey, out pv);

            string retrievedAppId;

            if (pv.IsNullOrEmpty)
            {
                retrievedAppId = "";
            }
            else
            {
                retrievedAppId = (string)pv.Value;
            }

            Marshal.ReleaseComObject(propertyStore);
            pv.Clear();

            return(retrievedAppId);
        }
예제 #6
0
        private void UpdateRichTextBox(IPropertyStore propertyStore)
        {
            FontPropertyStore fontPropertyStore = new FontPropertyStore(propertyStore);
            PropVariant       propValue;

            FontStyle fontStyle;
            string    family;
            float     size;

            if (richTextBox1.SelectionFont != null)
            {
                fontStyle = richTextBox1.SelectionFont.Style;
                family    = richTextBox1.SelectionFont.FontFamily.Name;
                size      = richTextBox1.SelectionFont.Size;
            }
            else
            {
                fontStyle = FontStyle.Regular;
                family    = string.Empty;
                size      = 0;
            }

            if (propertyStore.GetValue(ref RibbonProperties.FontProperties_Family, out propValue) == HRESULT.S_OK)
            {
                family = fontPropertyStore.Family;
            }
            if (propertyStore.GetValue(ref RibbonProperties.FontProperties_Size, out propValue) == HRESULT.S_OK)
            {
                size = (float)fontPropertyStore.Size;
            }

            // creating a new font can't fail if the font doesn't support the requested style
            // or if the font family name doesn't exist
            try
            {
                richTextBox1.SelectionFont = new Font(family, size, fontStyle);
            }
            catch (ArgumentException)
            {
            }
        }
예제 #7
0
        internal RibbonColors GetRibbonColors()
        {
            RibbonColors   colors        = new RibbonColors();
            IPropertyStore propertyStore = (IPropertyStore)ribbon.Framework;
            PropVariant    backgroundColorProp;
            PropVariant    highlightColorProp;
            PropVariant    textColorProp;

            // get ribbon colors
            propertyStore.GetValue(ref RibbonProperties.GlobalBackgroundColor, out backgroundColorProp);
            propertyStore.GetValue(ref RibbonProperties.GlobalHighlightColor, out highlightColorProp);
            propertyStore.GetValue(ref RibbonProperties.GlobalTextColor, out textColorProp);
            uint background = (uint)backgroundColorProp.Value;
            uint highlight  = (uint)highlightColorProp.Value;
            uint text       = (uint)textColorProp.Value;

            colors.BackgroundColor = ColorHelp.UInt32ToRGB(background);
            colors.HighlightColor  = ColorHelp.UInt32ToRGB(highlight);
            colors.TextColor       = ColorHelp.UInt32ToRGB(text);
            return(colors);
        }
예제 #8
0
        /*private static void InternalEnableCustomWindowPreview(IntPtr hwnd, bool enable)
         * {
         *  IntPtr t = Marshal.AllocHGlobal(4);
         *  Marshal.WriteInt32(t, enable ? 1 : 0);
         *
         *  try
         *  {
         *      int rc;
         *      rc = VistaBridgeInterop.UnsafeNativeMethods.DwmSetWindowAttribute(
         *          hwnd, SafeNativeMethods.DWMWA_HAS_ICONIC_BITMAP, t, 4);
         *      if (rc != 0)
         *          throw Marshal.GetExceptionForHR(rc);
         *
         *      rc = VistaBridgeInterop.UnsafeNativeMethods.DwmSetWindowAttribute(
         *          hwnd, SafeNativeMethods.DWMWA_FORCE_ICONIC_REPRESENTATION, t, 4);
         *      if (rc != 0)
         *          throw Marshal.GetExceptionForHR(rc);
         *  }
         *  finally
         *  {
         *      Marshal.FreeHGlobal(t);
         *  }
         * }*/

        #endregion

        #region Application Id

        /// <summary>
        /// Gets a window's application id by its window handle.
        /// </summary>
        /// <param name="hwnd">The window handle.</param>
        /// <returns>The application id of that window.</returns>
        public static string GetWindowAppId(IntPtr hwnd)
        {
            IPropertyStore propStore = InternalGetWindowPropertyStore(hwnd);

            PropVariant pv;

            propStore.GetValue(ref PropertyKey.PKEY_AppUserModel_ID, out pv);

            Marshal.ReleaseComObject(propStore);

            return(pv.GetValue());
        }
예제 #9
0
 public PropVariant GetValue(PropertyKey key)
 {
     if (Contains(key))
     {
         PropVariant result;
         HResult.Try(_propertyStoreInterface.GetValue(ref key, out result));
         return(result);
     }
     else
     {
         return(PropVariant.Empty);
     }
 }
예제 #10
0
        private object GetPropertyValue(IPropertyStore propertyStore, PROPERTYKEY propertyKey)
        {
            object      returnObj = null;
            PROPVARIANT propVariant;
            var         result = propertyStore.GetValue(ref propertyKey, out propVariant);

            AssertCoreAudio.IsHResultOk(result);

            var vType = (VarEnum)propVariant.vt;

            if (vType == VarEnum.VT_EMPTY)
            {
                return(null);
            }

            switch (vType)
            {
            case VarEnum.VT_BOOL:
                returnObj = propVariant.Data.AsBoolean;
                break;

            case VarEnum.VT_UI4:
                returnObj = propVariant.Data.AsUInt32;
                break;

            case VarEnum.VT_LPWSTR:
            case VarEnum.VT_CLSID:
                returnObj = Marshal.PtrToStringUni(propVariant.Data.AsStringPtr);
                break;

            case VarEnum.VT_BLOB:
                returnObj = propVariant.Data.AsFormatPtr;
                break;
            }

            if (propertyKey.fmtid == PropertyKeys.PKEY_AudioEngine_DeviceFormat ||
                propertyKey.fmtid == PropertyKeys.PKEY_AudioEngine_OEMFormat)
            {
                Assert.AreEqual(VarEnum.VT_BLOB, vType, "The device format property was not of varient type VT_BLOB.");
                var format = (WAVEFORMATEX)Marshal.PtrToStructure((IntPtr)returnObj, typeof(WAVEFORMATEX));

                if (format.nChannels != 0 && format.nSamplesPerSec != 0 && format.wBitsPerSample != 0)
                {
                    Assert.AreEqual(format.nChannels * format.nSamplesPerSec * format.wBitsPerSample, format.nAvgBytesPerSec * 8, "The wave format was not valid.");
                }
            }

            return(returnObj);
        }
예제 #11
0
        /// <summary>
        /// Get the three Colors of the Ribbon
        /// </summary>
        /// <returns>Ribbon Colors class or null</returns>
        public RibbonColors GetColors()
        {
            RibbonColors colors = null;

            if (!Initialized)
            {
                return(colors);
            }
            IPropertyStore propertyStore = (IPropertyStore)this.Framework;
            PropVariant    backgroundColorProp;
            PropVariant    highlightColorProp;
            PropVariant    textColorProp;

            // get ribbon colors
            propertyStore.GetValue(ref RibbonProperties.GlobalBackgroundColor, out backgroundColorProp);
            propertyStore.GetValue(ref RibbonProperties.GlobalHighlightColor, out highlightColorProp);
            propertyStore.GetValue(ref RibbonProperties.GlobalTextColor, out textColorProp);
            uint background = (uint)backgroundColorProp.Value;
            uint highlight  = (uint)highlightColorProp.Value;
            uint text       = (uint)textColorProp.Value;

            colors = new RibbonColors(ColorHelper.UInt32ToRGB(background), ColorHelper.UInt32ToRGB(highlight), ColorHelper.UInt32ToRGB(text));
            return(colors);
        }
예제 #12
0
        /// <summary>Clones a property store to a memory property store.</summary>
        /// <param name="ps">The property store to clone.</param>
        /// <returns>The cloned memory property store.</returns>
        /// <exception cref="System.ArgumentNullException">ps</exception>
        public static MemoryPropertyStore ClonePropertyStoreToMemory(IPropertyStore ps)
        {
            if (ps is null)
            {
                throw new ArgumentNullException(nameof(ps));
            }
            var ms  = new MemoryPropertyStore();
            var cnt = ps.GetCount();

            for (var i = 0U; i < cnt; i++)
            {
                var key = ps.GetAt(i);
                ms.Add(key, ps.GetValue(key));
            }
            return(ms);
        }
    public static string?GetString(this IPropertyStore propertyStore, PROPERTYKEY key)
    {
        if (propertyStore.GetValue(key, out var value).Failed)
        {
            return(null);
        }

        try
        {
            return(Marshal.PtrToStringUni(value.pwszVal));
        }
        finally
        {
            PInvoke.PropVariantClear(ref value);
        }
    }
예제 #14
0
 public bool TryGetValue(ShellItemPropertyKey key, out object value)
 {
     if (iprops != null)
     {
         try
         {
             var pv = new PROPVARIANT();
             iprops.GetValue(ref key, pv);
             value = pv.Value;
             return(true);
         }
         catch { }
     }
     value = null;
     return(false);
 }
예제 #15
0
        /// <summary>
        /// Gets the friendly name of the specified device.
        /// </summary>
        /// <param name="device">The <see cref="IMMDevice"/> interface of the device.</param>
        /// <returns>The friendly name of the device.</returns>
        internal static string GetDeviceFriendlyName(IMMDevice device)
        {
            string deviceId = device.GetId();

            IPropertyStore propertyStore = device.OpenPropertyStore(StgmRead);

            PropVariant friendlyNameProperty = propertyStore.GetValue(PKeyDeviceFriendlyName);

            Marshal.ReleaseComObject(propertyStore);

            string friendlyName = (string)friendlyNameProperty.Value;

            friendlyNameProperty.Clear();

            return(friendlyName);
        }
        private Dictionary <PropertyKey, object> GetProperties(IMMDevice device)
        {
            var properties = new Dictionary <PropertyKey, object>();

            //Opening in write mode, can cause exceptions to be thrown when not run as admin.
            //This tries to open in write mode if available
            try
            {
                Marshal.ThrowExceptionForHR(device.OpenPropertyStore(StorageAccessMode.ReadWrite, out _propertyStoreInteface));
                Mode = AccessMode.ReadWrite;
            }
            catch
            {
                Debug.WriteLine("Cannot open property store in write mode");
            }

            if (_propertyStoreInteface == null)
            {
                Marshal.ThrowExceptionForHR(device.OpenPropertyStore(StorageAccessMode.Read, out _propertyStoreInteface));
                Mode = AccessMode.Read;
            }
            try
            {
                uint count;
                _propertyStoreInteface.GetCount(out count);
                for (uint i = 0; i < count; i++)
                {
                    PropertyKey key;
                    PropVariant variant;
                    _propertyStoreInteface.GetAt(i, out key);

                    _propertyStoreInteface.GetValue(ref key, out variant);

                    if (variant.IsSupported())
                    {
                        properties.Add(key, variant.Value);
                    }
                }
            }
            catch
            {
                Debug.WriteLine("Cannot get property values");
                return(new Dictionary <PropertyKey, object>());
            }

            return(properties);
        }
예제 #17
0
 public PropertyStoreProperty this[PropertyKey queryKey]
 {
     get
     {
         for (var i = 0; i < Count; i++)
         {
             var key = Get(i);
             if (key.fmtid == queryKey.fmtid && key.pid == queryKey.pid)
             {
                 PropVariant result;
                 Marshal.ThrowExceptionForHR(_Store.GetValue(ref key, out result));
                 return(new PropertyStoreProperty(result));
             }
         }
         return(null);
     }
 }
예제 #18
0
        private static JumpItem GetJumpItemForShellObject(object shellObject)
        {
            IShellItem2 shellItem  = shellObject as IShellItem2;
            IShellLinkW shellLinkW = shellObject as IShellLinkW;

            if (shellItem != null)
            {
                return(new JumpPath
                {
                    Path = shellItem.GetDisplayName((SIGDN)2147647488u)
                });
            }
            if (shellLinkW != null)
            {
                StringBuilder stringBuilder = new StringBuilder(260);
                shellLinkW.GetPath(stringBuilder, stringBuilder.Capacity, null, SLGP.RAWPATH);
                StringBuilder stringBuilder2 = new StringBuilder(1024);
                shellLinkW.GetArguments(stringBuilder2, stringBuilder2.Capacity);
                StringBuilder stringBuilder3 = new StringBuilder(1024);
                shellLinkW.GetDescription(stringBuilder3, stringBuilder3.Capacity);
                StringBuilder stringBuilder4 = new StringBuilder(260);
                int           iconResourceIndex;
                shellLinkW.GetIconLocation(stringBuilder4, stringBuilder4.Capacity, out iconResourceIndex);
                StringBuilder stringBuilder5 = new StringBuilder(260);
                shellLinkW.GetWorkingDirectory(stringBuilder5, stringBuilder5.Capacity);
                JumpTask jumpTask = new JumpTask
                {
                    ApplicationPath   = stringBuilder.ToString(),
                    Arguments         = stringBuilder2.ToString(),
                    Description       = stringBuilder3.ToString(),
                    IconResourceIndex = iconResourceIndex,
                    IconResourcePath  = stringBuilder4.ToString(),
                    WorkingDirectory  = stringBuilder5.ToString()
                };
                using (PROPVARIANT propvariant = new PROPVARIANT())
                {
                    IPropertyStore propertyStore = (IPropertyStore)shellLinkW;
                    PKEY           title         = PKEY.Title;
                    propertyStore.GetValue(ref title, propvariant);
                    jumpTask.Title = (propvariant.GetValue() ?? "");
                }
                return(jumpTask);
            }
            return(null);
        }
    public static string[] GetStringArray(this IPropertyStore propertyStore, PROPERTYKEY key)
    {
        if (propertyStore.GetValue(key, out var value).Failed)
        {
            return(Array.Empty <string>());
        }

        try
        {
            return(Enumerable.Range(0, (int)value.calpwstr.cElems)
                   .Select(x => Marshal.PtrToStringUni(Marshal.ReadIntPtr(value.calpwstr.pElems, x * IntPtr.Size)) !)
                   .ToArray());
        }
        finally
        {
            PInvoke.PropVariantClear(ref value);
        }
    }
        /// <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

        }
예제 #21
0
        private static string ShellLinkToString(IShellLinkW shellLink)
        {
            StringBuilder stringBuilder = new StringBuilder(260);

            shellLink.GetPath(stringBuilder, stringBuilder.Capacity, null, SLGP.RAWPATH);
            string text = null;

            using (PROPVARIANT propvariant = new PROPVARIANT())
            {
                IPropertyStore propertyStore = (IPropertyStore)shellLink;
                PKEY           title         = PKEY.Title;
                propertyStore.GetValue(ref title, propvariant);
                text = (propvariant.GetValue() ?? "");
            }
            StringBuilder stringBuilder2 = new StringBuilder(1024);

            shellLink.GetArguments(stringBuilder2, stringBuilder2.Capacity);
            return(stringBuilder.ToString().ToUpperInvariant() + text.ToUpperInvariant() + stringBuilder2.ToString());
        }
예제 #22
0
        public static T GetValue <T>(this IPropertyStore propStore, PROPERTYKEY key)
        {
            PropVariant pv = default(PropVariant);

            try
            {
                pv = propStore.GetValue(ref key);
                switch (pv.varType)
                {
                case VarEnum.VT_LPWSTR:
                    return((T)Convert.ChangeType(Marshal.PtrToStringUni(pv.pwszVal), typeof(T)));

                default: throw new NotImplementedException();
                }
            }
            finally
            {
                Ole32.PropVariantClear(ref pv);
            }
        }
예제 #23
0
        private void _UpdateSubitemValuesThreadRun()
        {
            while (true)
            {
                var index = this._ItemsForSubitemsUpdate.Dequeue();
                if (User32.SendMessage(this._ShellViewEx.LVHandle, Interop.MSG.LVM_ISITEMVISIBLE, index.Item1, 0) != IntPtr.Zero)
                {
                    var currentItem = this._ShellViewEx.Items[index.Item1];
                    var temp        = currentItem.Clone();
                    var isi2        = (IShellItem2)temp.ComInterface;
                    var pvar        = new PropVariant();
                    var pk          = index.Item3;
                    if (pk.fmtid == SystemProperties.DriveFreeSpace.fmtid && pk.pid == SystemProperties.DriveFreeSpace.pid)
                    {
                        continue;
                    }
                    var            guid      = new Guid(InterfaceGuids.IPropertyStore);
                    IPropertyStore propStore = null;
                    isi2.GetPropertyStore(GetPropertyStoreOptions.Default, ref guid, out propStore);
                    if (propStore != null && propStore.GetValue(ref pk, pvar) == HResult.S_OK)
                    {
                        if (currentItem.ColumnValues.Keys.ToArray().Count(s => s.fmtid == pk.fmtid && s.pid == pk.pid) == 0)
                        {
                            try {
                                currentItem.ColumnValues.Add(pk, pvar.Value);
                                if (!this._RedrawQueue.Contains(index.Item1))
                                {
                                    this._RedrawQueue.Enqueue(index.Item1);
                                }
                            } catch {
                                //TODO: Fix this try-catch!!!!!
                            }
                        }

                        pvar.Dispose();
                        Marshal.ReleaseComObject(propStore);
                    }
                    temp.Dispose();
                }
            }
        }
        private void GetImageReference()
        {
            IPropertyStore store = ShellPropertyCollection.CreateDefaultPropertyStore(ParentShellObject);

#if CS7

            using (var propVar = new PropVariant())

            {

#else

            using var propVar = new PropVariant();

#endif

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

            _ = Marshal.ReleaseComObject(store);
            store = null;

            ((IPropertyDescription2)Description.NativePropertyDescription).GetImageReferenceForValue(
                propVar, out string refPath);

            if (refPath == null) return;

            int index = Win32Native.Shell.Shell.PathParseIconLocation(ref refPath);

            if (refPath != null)
            {
                imageReferencePath = refPath;
                imageReferenceIconIndex = index;
            }

#if CS7

            }

#endif

        }
예제 #25
0
        //Get all the playback audio devices
        public static List <AudioDeviceSummary> ListAudioDevices()
        {
            try
            {
                List <AudioDeviceSummary> deviceListSummary = new List <AudioDeviceSummary>();
                IMMDeviceEnumerator       deviceEnumerator  = (IMMDeviceEnumerator) new MMDeviceEnumerator();
                IMMDeviceCollection       deviceCollection  = deviceEnumerator.EnumAudioEndpoints(EDataFlow.eRender, DeviceState.ACTIVE);

                uint deviceCount = deviceCollection.GetCount();
                for (uint deviceIndex = 0; deviceIndex < deviceCount; deviceIndex++)
                {
                    IMMDevice.IMMDevice deviceItem = deviceCollection.Item(deviceIndex);

                    //Get the audio device id
                    string deviceId = deviceItem.GetId();

                    //Get the audio device name
                    PropertyVariant propertyVariant = new PropertyVariant();
                    IPropertyStore  propertyStore   = deviceItem.OpenPropertyStore(STGM.STGM_READ);
                    propertyStore.GetValue(ref PKEY_Device_FriendlyName, out propertyVariant);
                    string deviceName = Marshal.PtrToStringUni(propertyVariant.pwszVal);

                    //Add device to summary list
                    deviceListSummary.Add(new AudioDeviceSummary()
                    {
                        Identifier = deviceId, Name = deviceName
                    });
                }

                return(deviceListSummary);
            }
            catch
            {
                Debug.WriteLine("Failed to get audio devices.");
                return(null);
            }
        }
예제 #26
0
        // T7E: Gets property store for shortcut
        public string GetApplicationIdForShortcut(string shortcutPath)
        {
            // Get shell item
            IShellItem2 shellItem;
            Guid        guid = new Guid(ShellIIDGuid.IShellItem2);
            int         hrc  = ShellNativeMethods.SHCreateItemFromParsingName(shortcutPath, IntPtr.Zero, ref guid, out shellItem);

            // Get property store
            Guid           psGuid    = new Guid(ShellIIDGuid.IPropertyStore);
            IPropertyStore propStore = null;
            int            hr        = shellItem.GetPropertyStore(
                ShellNativeMethods.GETPROPERTYSTOREFLAGS.GPS_READWRITE,
                ref psGuid,
                out propStore);

            // Get appid property
            PropVariant pv       = new PropVariant();
            PropertyKey AppIdKey = new PropertyKey(new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 5);

            propStore.GetValue(ref AppIdKey, out pv);

            string retrievedAppId;

            if (pv.IsNullOrEmpty)
            {
                retrievedAppId = "";
            }
            else
            {
                retrievedAppId = (string)pv.Value;
            }

            Marshal.ReleaseComObject(propStore);
            pv.Clear();

            return(retrievedAppId);
        }
        private static PropVariant GetProperty(IntPtr hwnd, PropertyKey key)
        {
            IPropertyStore propStore = null;
            PropVariant    pv;

            try
            {
                propStore = GetWindowPropertyStore(hwnd);
                propStore.GetValue(ref key, out pv);
            }
            catch
            {
                pv = new PropVariant();
            }
            finally
            {
                if (propStore != null)
                {
                    Marshal.ReleaseComObject(propStore);
                }
            }

            return(pv);
        }
예제 #28
0
        private static bool SetShortcut()
        {
            bool writeShortcut = false;

            PROPERTYKEY appModelIDKey = PROPERTYKEY.System.AppUserModel.ID;

            IShellLinkW    shortcut      = (IShellLinkW) new CShellLinkW();
            IPersistFile   persistFile   = (IPersistFile)shortcut;
            IPropertyStore propertyStore = (IPropertyStore)shortcut;

            try
            {
                persistFile.Load(LINKFILE_PATH, (int)Vanara.PInvoke.STGM.STGM_READ);
            }
            catch (System.IO.FileNotFoundException)
            {
                writeShortcut = true;

                // This is possibly first invocation so set registry in order to persist in Action Center
                ConfigureRegistry();
            }

            if (!writeShortcut)
            {
                StringBuilder curPath = new StringBuilder(Vanara.PInvoke.Kernel32.MAX_PATH);
                shortcut.GetPath(curPath, curPath.Capacity, null, SLGP.SLGP_RAWPATH);

                if (!EXE_PATH.Equals(curPath.ToString(), StringComparison.OrdinalIgnoreCase))
                {
                    writeShortcut = true;
                }
            }

            if (!writeShortcut)
            {
                StringBuilder curArgs = new StringBuilder(Vanara.PInvoke.ComCtl32.INFOTIPSIZE);
                shortcut.GetArguments(curArgs, curArgs.Capacity);

                if (!SHORTCUT_ARGUMENTS.Equals(curArgs.ToString(), StringComparison.Ordinal))
                {
                    writeShortcut = true;
                }
            }

            if (!writeShortcut)
            {
                using (PROPVARIANT pv = new PROPVARIANT())
                {
                    propertyStore.GetValue(ref appModelIDKey, pv);
                    if (!APP_ID.Equals(pv.pwszVal, StringComparison.Ordinal))
                    {
                        writeShortcut = true;
                    }
                }
            }

            if (writeShortcut)
            {
                shortcut.SetPath(EXE_PATH);
                shortcut.SetArguments(string.Empty);

                using (PROPVARIANT pv = new PROPVARIANT(APP_ID))
                {
                    propertyStore.SetValue(ref appModelIDKey, pv);
                    propertyStore.Commit();
                }

                persistFile.Save(LINKFILE_PATH, true);

                return(true);
            }

            return(false);
        }
예제 #29
0
        private object GetPropertyValue(IPropertyStore propertyStore, PROPERTYKEY propertyKey)
        {
            object returnObj = null;
            PROPVARIANT propVariant;
            var result = propertyStore.GetValue(ref propertyKey, out propVariant);
            AssertCoreAudio.IsHResultOk(result);

            var vType = (VarEnum)propVariant.vt;
            if (vType == VarEnum.VT_EMPTY)
                return null;

            switch (vType)
            {
                case VarEnum.VT_BOOL:
                    returnObj = propVariant.Data.AsBoolean;
                    break;
                case VarEnum.VT_UI4:
                    returnObj = propVariant.Data.AsUInt32;
                    break;
                case VarEnum.VT_LPWSTR:
                case VarEnum.VT_CLSID:
                    returnObj = Marshal.PtrToStringUni(propVariant.Data.AsStringPtr);
                    break;
                case VarEnum.VT_BLOB:
                    returnObj = propVariant.Data.AsFormatPtr;
                    break;
            }

            if (propertyKey.fmtid == PropertyKeys.PKEY_AudioEngine_DeviceFormat ||
                propertyKey.fmtid == PropertyKeys.PKEY_AudioEngine_OEMFormat)
            {
                Assert.AreEqual(VarEnum.VT_BLOB, vType, "The device format property was not of varient type VT_BLOB.");
                var format = (WAVEFORMATEX)Marshal.PtrToStructure((IntPtr)returnObj, typeof(WAVEFORMATEX));

                if (format.nChannels != 0 && format.nSamplesPerSec != 0 && format.wBitsPerSample != 0)
                    Assert.AreEqual(format.nChannels * format.nSamplesPerSec * format.wBitsPerSample, format.nAvgBytesPerSec * 8, "The wave format was not valid.");
            }

            return returnObj;
        }
예제 #30
0
        static void Main(string[] args)
        {
            if (args.Length == 2 && args[0] == "/get")
            {
                var          fp   = args[1];
                IShellLinkW  plnk = (IShellLinkW) new CShellLink();
                IPersistFile ppf  = (IPersistFile)plnk;
                ppf.Load(fp, STGM_READ);
                // http://8thway.blogspot.jp/2012/11/csharp-appusermodelid.html
                IPropertyStore pps = (IPropertyStore)plnk;
                PropVariant    v   = new PropVariant();
                pps.GetValue(ref AppUserModelIDKey, ref v);

                String s = "";
                if (v.vt == VT_BSTR)
                {
                    s = Marshal.PtrToStringUni(v.pVal);
                }
                if (v.vt == VT_LPWSTR)
                {
                    s = Marshal.PtrToStringUni(v.pVal);
                }

                Console.WriteLine(s);
            }
            else if (args.Length == 2 && args[0] == "/list")
            {
                var          fp   = args[1];
                IShellLinkW  plnk = (IShellLinkW) new CShellLink();
                IPersistFile ppf  = (IPersistFile)plnk;
                ppf.Load(fp, STGM_READ);
                IPropertyStore pps = (IPropertyStore)plnk;
                uint           cx;
                pps.GetCount(out cx);
                for (uint x = 0; x < cx; x++)
                {
                    PropertyKey k = new PropertyKey();
                    pps.GetAt(x, ref k);
                    PropVariant v = new PropVariant();
                    pps.GetValue(ref k, ref v);
                    String s = "";
                    if (v.vt == VT_BSTR)
                    {
                        s = Marshal.PtrToStringUni(v.pVal);
                    }
                    if (v.vt == VT_LPWSTR)
                    {
                        s = Marshal.PtrToStringUni(v.pVal);
                    }
                    Console.WriteLine(k.fmtid.ToString("B") + " " + k.pid + " " + v.vt + " " + s);
                }
            }
            else if (args.Length == 3 && args[0] == "/set")
            {
                var          fp   = args[1];
                var          s    = args[2];
                IShellLinkW  plnk = (IShellLinkW) new CShellLink();
                IPersistFile ppf  = (IPersistFile)plnk;
                ppf.Load(fp, STGM_READWRITE);
                // http://8thway.blogspot.jp/2012/11/csharp-appusermodelid.html
                IPropertyStore pps = (IPropertyStore)plnk;
                PropVariant    pv  = new PropVariant {
                    vt   = VT_LPWSTR,
                    pVal = Marshal.StringToBSTR(s)
                };
                pps.SetValue(ref AppUserModelIDKey, ref pv);
                pps.Commit();
                ppf.Save(fp, false);
            }
            else
            {
                helpYa();
            }
        }
예제 #31
0
        /// <summary>
        /// Based on https://docs.microsoft.com/en-us/windows/desktop/medfound/shell-metadata-providers
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void infoToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IMFSourceResolver pSourceResolver = null;
            IMFMediaSource    pSource         = null;
            object            pPropsObject    = null;
            var url = this.listView1.SelectedItems[0].Text;

            try
            {
                // Create the source resolver.
                HResult hr = MFExtern.MFCreateSourceResolver(out pSourceResolver);
                Validate(hr);
                if (pSourceResolver == null)
                {
                    throw new Exception("pSourceResolver is null");
                }
                // Get a pointer to the IMFMediaSource interface of the media source.
                hr = pSourceResolver.CreateObjectFromURL(url, MFResolution.MediaSource, null, out pSource);
                Validate(hr);
                if (pSource == null)
                {
                    throw new Exception("pSource is null");
                }

                hr = MFExtern.MFGetService(pSource, MFServices.MF_PROPERTY_HANDLER_SERVICE, typeof(IPropertyStore).GUID, out pPropsObject);
                Validate(hr);
                if (pPropsObject == null)
                {
                    throw new Exception("pPropsObject is null");
                }
                IPropertyStore pProps = pPropsObject as IPropertyStore;

                hr = pProps.GetCount(out int cProps);
                Validate(hr);

                var audioInfo = new AudioInfo();
                var videoInfo = new VideoInfo();

                for (int i = 0; i < cProps; ++i)
                {
                    var key = new MediaFoundation.Misc.PropertyKey();
                    hr = pProps.GetAt(i, key);
                    Validate(hr);

                    using (PropVariant pv = new PropVariant())
                    {
                        hr = pProps.GetValue(key, pv);
                        Validate(hr);
                        FillAudioProperty(audioInfo, key, pv);
                        FillVideoProperty(videoInfo, key, pv);
                    }
                }
                MessageBox.Show("Audio =\n" + audioInfo + ";\nVideo =\n" + videoInfo);
            }
            finally
            {
                if (pSource != null)
                {
                    Marshal.ReleaseComObject(pSource);
                }
                if (pSourceResolver != null)
                {
                    Marshal.ReleaseComObject(pSourceResolver);
                }
                if (pPropsObject != null)
                {
                    Marshal.ReleaseComObject(pPropsObject);
                }
            }
            // MessageBox.Show(url);
        }