private void InstallShortcut(String shortcutPath) { // Find the path to the current executable String exePath = Process.GetCurrentProcess().MainModule.FileName; IShellLinkW newShortcut = (IShellLinkW) new CShellLink(); // Create a shortcut to the exe ErrorHelper.VerifySucceeded(newShortcut.SetPath(exePath)); ErrorHelper.VerifySucceeded(newShortcut.SetArguments("")); // Open the shortcut property store, set the AppUserModelId property IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut; using (PropVariant appId = new PropVariant(_config.StaticConfig.ToastAppID)) { ErrorHelper.VerifySucceeded(newShortcutProperties.SetValue(SystemProperties.System.AppUserModel.ID, appId)); ErrorHelper.VerifySucceeded(newShortcutProperties.Commit()); } using (PropVariant guid = new PropVariant(_config.StaticConfig.ToastActivatorCLSID)) { ErrorHelper.VerifySucceeded(newShortcutProperties.SetValue(SystemProperties.System.AppUserModel.ToastActivatorCLSID, guid)); ErrorHelper.VerifySucceeded(newShortcutProperties.Commit()); } // Commit the shortcut to disk IPersistFile newShortcutSave = (IPersistFile)newShortcut; ErrorHelper.VerifySucceeded(newShortcutSave.Save(shortcutPath, true)); }
private void InstallShortcut(String shortcutPath, String exePath) { IShellLinkW newShortcut = (IShellLinkW) new CShellLink(); // Create a shortcut to the exe newShortcut.SetPath(exePath); // Open the shortcut property store, set the AppUserModelId property IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut; PropVariantHelper varAppId = new PropVariantHelper(); varAppId.SetValue(APP_ID); newShortcutProperties.SetValue(PROPERTYKEY.AppUserModel_ID, varAppId.Propvariant); PropVariantHelper varToastId = new PropVariantHelper(); varToastId.VarType = VarEnum.VT_CLSID; varToastId.SetValue(typeof(NotificationActivator).GUID); newShortcutProperties.SetValue(PROPERTYKEY.AppUserModel_ToastActivatorCLSID, varToastId.Propvariant); // Commit the shortcut to disk ShellHelpers.IPersistFile newShortcutSave = (ShellHelpers.IPersistFile)newShortcut; newShortcutSave.Save(shortcutPath, true); }
/** * Adds a new shortcut for the specified executable and app id. */ public static void InstallShortcut(string exePath, string appId, Guid handler) { // Start a new shortcut object for our new shortcut. IShellLinkW newShortcut = (IShellLinkW) new CShellLink(); newShortcut.SetPath(exePath); // Set our classid and handler GUID for the shortcut. IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut; PropVariantHelper varAppId = new PropVariantHelper(); varAppId.SetValue(appId); newShortcutProperties.SetValue(PROPERTYKEY.AppUserModel_ID, varAppId.Propvariant); PropVariantHelper varToastId = new PropVariantHelper(); varToastId.VarType = VarEnum.VT_CLSID; varToastId.SetValue(handler); newShortcutProperties.SetValue(PROPERTYKEY.AppUserModel_ToastActivatorCLSID, varToastId.Propvariant); // Save the shortcut. IPersistFile newShortcutSave = (IPersistFile)newShortcut; newShortcutSave.Save(SHORTCUT_PATH, true); }
/// <summary> /// Change ribbon background, highlight and text colors /// </summary> /// <param name="background">new background color</param> /// <param name="highlight">new highlight color</param> /// <param name="text">new text color</param> public void SetColors(Color background, Color highlight, Color text) { if (!Initalized) { return; } // convert colors to proper color format uint backgroundColor = ColorHelper.HSB2Uint(ColorHelper.HSL2HSB(ColorHelper.RGB2HSL(background))); uint highlightColor = ColorHelper.HSB2Uint(ColorHelper.HSL2HSB(ColorHelper.RGB2HSL(highlight))); uint textColor = ColorHelper.HSB2Uint(ColorHelper.HSL2HSB(ColorHelper.RGB2HSL(text))); IPropertyStore propertyStore = (IPropertyStore)Framework; PropVariant backgroundColorProp = PropVariant.FromObject(backgroundColor); PropVariant highlightColorProp = PropVariant.FromObject(highlightColor); PropVariant textColorProp = PropVariant.FromObject(textColor); // set ribbon colors propertyStore.SetValue(ref RibbonProperties.GlobalBackgroundColor, ref backgroundColorProp); propertyStore.SetValue(ref RibbonProperties.GlobalHighlightColor, ref highlightColorProp); propertyStore.SetValue(ref RibbonProperties.GlobalTextColor, ref textColorProp); propertyStore.Commit(); }
private static void CreateShortcut(string shortcutPath, string exePath) { IShellLinkW newShortcut = (IShellLinkW) new CShellLink(); newShortcut.SetPath(exePath); IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut; PropVariantHelper varAppId = new PropVariantHelper(); varAppId.SetValue(Constants.AppId); newShortcutProperties.SetValue(PROPERTYKEY.AppUserModel_ID, varAppId.Propvariant); PropVariantHelper varToastId = new PropVariantHelper(); varToastId.VarType = VarEnum.VT_CLSID; varToastId.SetValue(typeof(NotificationActivator).GUID); newShortcutProperties.SetValue(PROPERTYKEY.AppUserModel_ToastActivatorCLSID, varToastId.Propvariant); newShortcutProperties.Commit(); IPersistFile newShortcutSave = (IPersistFile)newShortcut; newShortcutSave.Save(shortcutPath, true); }
/// <summary> /// Gets the shell <b>IShellLink</b> representation /// of the object. /// </summary> /// <returns>An <b>IShellLink</b> up-cast to <b>object</b>.</returns> public object GetShellRepresentation() { IShellLinkW shellLink = (IShellLinkW) new CShellLink(); IPropertyStore propertyStore = (IPropertyStore)shellLink; PropVariant propVariant = new PropVariant(); if (IsSeparator) { propVariant.SetValue(true); HResult setValueResult = propertyStore.SetValue(ref PropertyKey.PKEY_AppUserModel_IsDestListSeparator, ref propVariant); setValueResult.ThrowIf(); propVariant.Clear(); propVariant.Dispose(); } else { HResult setPathResult = shellLink.SetPath(Path); setPathResult.ThrowIf(); if (!String.IsNullOrEmpty(IconLocation)) { HResult setIconLocationResult = shellLink.SetIconLocation(IconLocation, IconIndex); setIconLocationResult.ThrowIf(); } if (!String.IsNullOrEmpty(Arguments)) { HResult setArgumentsResult = shellLink.SetArguments(Arguments); setArgumentsResult.ThrowIf(); } if (!String.IsNullOrEmpty(WorkingDirectory)) { HResult setWorkingDirectoryResult = shellLink.SetWorkingDirectory(WorkingDirectory); setWorkingDirectoryResult.ThrowIf(); } HResult setShowCmdResult = shellLink.SetShowCmd((uint)ShowCommand); setShowCmdResult.ThrowIf(); propVariant.SetValue(Title); HResult setValueResult = propertyStore.SetValue(ref PropertyKey.PKEY_Title, ref propVariant); setValueResult.ThrowIf(); propVariant.Clear(); propVariant.Dispose(); } HResult commitResult = propertyStore.Commit(); commitResult.ThrowIf(); //Marshal.ReleaseComObject(propertyStore); return(shellLink); }
/// <summary> /// Sets a property value. /// </summary> /// <param name="propertyStore">The property store to set the property in.</param> /// <param name="property">The property to set.</param> /// <param name="value">The value to set the property to.</param> private static void SetPropertyValue(IPropertyStore propertyStore, PropertyKey property, string value) { var variant = new PropertyVariant(value); propertyStore.SetValue(ref property, ref variant); variant.Dispose(); }
private static void InstallShortcut(string appIdStr, string exePath, string shortcutPath, string arguments = "") { if (File.Exists(shortcutPath)) { Console.Error.WriteLine("warning: overwriting existing shortcut"); } // Find the path to the current executable IShellLinkW newShortcut = (IShellLinkW) new CShellLink(); // Create a shortcut to the exe ShellHelpers.ErrorHelper.VerifySucceeded(newShortcut.SetPath(exePath)); ShellHelpers.ErrorHelper.VerifySucceeded(newShortcut.SetArguments(arguments)); // Open the shortcut property store, set the AppUserModelId property IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut; using (PropVariant appId = new PropVariant(appIdStr)) { ShellHelpers.ErrorHelper.VerifySucceeded(newShortcutProperties.SetValue(SystemProperties.System.AppUserModel.ID, appId)); ShellHelpers.ErrorHelper.VerifySucceeded(newShortcutProperties.Commit()); } // Commit the shortcut to disk IPersistFile newShortcutSave = (IPersistFile)newShortcut; ShellHelpers.ErrorHelper.VerifySucceeded(newShortcutSave.Save(shortcutPath, true)); }
// T7E: Gets property store for shortcut public void SetApplicationIdForShortcut(string shortcutPath, string appId) { // 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); // Set appid property PropVariant pv = new PropVariant(); PropertyKey AppIdKey = new PropertyKey(new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 5); pv.SetString(appId); propStore.SetValue(ref AppIdKey, ref pv); propStore.Commit(); Marshal.ReleaseComObject(propStore); pv.Clear(); }
static void InstallShortcut(string appId, string shortcutPath) { // Find the path to the current executable String exePath = Process.GetCurrentProcess().MainModule.FileName; IShellLinkW newShortcut = (IShellLinkW) new CShellLink(); // Create a shortcut to the exe VerifySucceeded(newShortcut.SetPath(exePath)); VerifySucceeded(newShortcut.SetArguments("")); // Open the shortcut property store, set the AppUserModelId property IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut; using (PropVariant applicationId = new PropVariant(appId)) { VerifySucceeded(newShortcutProperties.SetValue( SystemProperties.System.AppUserModel.ID, applicationId)); VerifySucceeded(newShortcutProperties.Commit()); } // Commit the shortcut to disk IPersistFile newShortcutSave = (IPersistFile)newShortcut; VerifySucceeded(newShortcutSave.Save(shortcutPath, true)); }
public static void InstallShortcut(string exePath, string appId, string desc, string wkDirec, string iconLocation, string saveLocation, string arguments) { // Use passed parameters as to construct the shortcut IShellLinkW newShortcut = (IShellLinkW) new CShellLink(); newShortcut.SetPath(exePath); newShortcut.SetDescription(desc); newShortcut.SetWorkingDirectory(wkDirec); newShortcut.SetArguments(arguments); newShortcut.SetIconLocation(iconLocation, 0); // Set the classID of the shortcut that is created // Crucial to avoid program stacking IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut; PropVariantHelper varAppId = new PropVariantHelper(); varAppId.SetValue(appId); newShortcutProperties.SetValue(PROPERTYKEY.AppUserModel_ID, varAppId.Propvariant); // Save the shortcut as per passed save location IPersistFile newShortcutSave = (IPersistFile)newShortcut; newShortcutSave.Save(saveLocation, true); }
/// <summary> /// Writes the given property key and value. To allow truncation of the given value, set allowTruncatedValue /// to true. /// </summary> /// <param name="key">The property key.</param> /// <param name="value">The value associated with the key.</param> /// <param name="allowTruncatedValue">True to allow truncation (default); otherwise False.</param> /// <exception cref="System.InvalidOperationException">If the writable property store is already /// closed.</exception> /// <exception cref="System.ArgumentOutOfRangeException">If AllowTruncatedValue is set to false /// and while setting the value on the property it had to be truncated in a string or rounded in /// a numeric value.</exception> public void WriteProperty(PropertyKey key, object value, bool allowTruncatedValue) { if (writablePropStore == null) { throw new InvalidOperationException("Writeable store has been closed."); } PropVariant propVar = PropVariant.FromObject(value); int result = writablePropStore.SetValue(ref key, ref propVar); if (!allowTruncatedValue && (result == InPlaceStringTruncated)) { // At this point we can't revert back the commit // so don't commit, close the property store and throw an exception // to let the user know. Marshal.ReleaseComObject(writablePropStore); writablePropStore = null; throw new ArgumentOutOfRangeException("value", "A value had to be truncated in a string or rounded if a numeric value. Set AllowTruncatedValue to true to prevent this exception."); } if (!CoreErrorHelper.Succeeded(result)) { throw new ExternalException("Unable to set property.", Marshal.GetExceptionForHR(result)); } }
/// <summary> /// Writes the given property key and value. To allow truncation of the given value, set allowTruncatedValue /// to true. /// </summary> /// <param name="key">The property key.</param> /// <param name="value">The value associated with the key.</param> /// <param name="allowTruncatedValue">True to allow truncation (default); otherwise False.</param> /// <exception cref="System.InvalidOperationException">If the writable property store is already /// closed.</exception> /// <exception cref="System.ArgumentOutOfRangeException">If AllowTruncatedValue is set to false /// and while setting the value on the property it had to be truncated in a string or rounded in /// a numeric value.</exception> public void WriteProperty(PropertyKey key, object value, bool allowTruncatedValue) { if (writablePropStore == null) { throw new InvalidOperationException("Writeable store has been closed."); } using (PropVariant propVar = PropVariant.FromObject(value)) { HResult result = writablePropStore.SetValue(ref key, propVar); if (!allowTruncatedValue && ((int)result == ShellNativeMethods.InPlaceStringTruncated)) { // At this point we can't revert back the commit // so don't commit, close the property store and throw an exception // to let the user know. Marshal.ReleaseComObject(writablePropStore); writablePropStore = null; throw new ArgumentOutOfRangeException("value", LocalizedMessages.ShellPropertyValueTruncated); } if (!CoreErrorHelper.Succeeded(result)) { throw new PropertySystemException(LocalizedMessages.ShellPropertySetValue, Marshal.GetExceptionForHR((int)result)); } } }
public static void ClearWindowAppId(IntPtr hwnd) { IPropertyStore propStore = InternalGetWindowPropertyStore(hwnd); PropVariant pv = new PropVariant(); pv.Clear(); propStore.SetValue(ref PropertyKey.PKEY_AppUserModel_ID, ref pv); Marshal.ReleaseComObject(propStore); }
private void StorePropVariantValue(PropVariant propVar) { var guid = new Guid(NativeAPI.Guids.Shell.IPropertyStore); IPropertyStore writablePropStore = null; try { int hr = ParentShellObject.NativeShellItem2.GetPropertyStore( 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 && result == HResult.InPlaceStringTruncated) { throw new ArgumentOutOfRangeException(nameof(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; } } }
private static IShellLink CreateShellLink(string title, string path, string arguments, string icon_path, int icon_pos) { try { IShellLink shell_link = (IShellLink)Activator.CreateInstance(Type.GetTypeFromCLSID(CLSID.ShellLink)); shell_link.SetPath(path); if (!string.IsNullOrEmpty(arguments)) { shell_link.SetArguments(arguments); } if (!string.IsNullOrEmpty(icon_path)) { shell_link.SetIconLocation(icon_path, icon_pos); } IntPtr pps; Guid ipsiid = CLSID.IPropertyStore; Marshal.QueryInterface(Marshal.GetIUnknownForObject(shell_link), ref ipsiid, out pps); IPropertyStore property_store = (IPropertyStore)Marshal.GetTypedObjectForIUnknown(pps, typeof(IPropertyStore)); PROPVARIANT propvar = new PROPVARIANT(); propvar.SetString(title); // PKEY_Title PROPERTYKEY PKEY_Title = new PROPERTYKEY(); PKEY_Title.fmtid = new Guid("F29F85E0-4FF9-1068-AB91-08002B27B3D9"); PKEY_Title.pid = 2; property_store.SetValue(ref PKEY_Title, ref propvar); property_store.Commit(); IntPtr psl; Guid psliid = CLSID.IShellLinkW; Marshal.QueryInterface(Marshal.GetIUnknownForObject(shell_link), ref psliid, out psl); IShellLink link = (IShellLink)Marshal.GetTypedObjectForIUnknown(psl, typeof(IShellLink)); propvar.Clear(); Marshal.ReleaseComObject(property_store); property_store = null; Marshal.ReleaseComObject(shell_link); shell_link = null; return(link); } catch (COMException e) { Logger.Error("Error createing shell link: {0}\n{1}", e.Message, e.StackTrace); } return(null); }
public object this[ShellItemPropertyKey key] { get { object r; if (!TryGetValue(key, out r)) { throw new ArgumentOutOfRangeException(nameof(key)); } return(r); } set { if (iprops == null) { throw new InvalidOperationException("Property store does not exist."); } iprops.SetValue(key, new PROPVARIANT(value)); OnPropertyChanged(); } }
/// <summary> /// Gets the shell <b>IShellLink</b> representation /// of the object. /// </summary> /// <returns>An <b>IShellLink</b> up-cast to <b>object</b>.</returns> public object GetShellRepresentation() { IShellLinkW shellLink = (IShellLinkW) new CShellLink(); IPropertyStore propertyStore = (IPropertyStore)shellLink; PropVariant propVariant = new PropVariant(); if (IsSeparator) { propVariant.SetValue(true); propertyStore.SetValue(ref PropertyKey.PKEY_AppUserModel_IsDestListSeparator, ref propVariant); propVariant.Clear(); } else { shellLink.SetPath(Path); if (!String.IsNullOrEmpty(IconLocation)) { shellLink.SetIconLocation(IconLocation, IconIndex); } if (!String.IsNullOrEmpty(Arguments)) { shellLink.SetArguments(Arguments); } if (!String.IsNullOrEmpty(WorkingDirectory)) { shellLink.SetWorkingDirectory(WorkingDirectory); } shellLink.SetShowCmd((uint)ShowCommand); propVariant.SetValue(Title); propertyStore.SetValue(ref PropertyKey.PKEY_Title, ref propVariant); propVariant.Clear(); } propertyStore.Commit(); return(shellLink); }
private static bool Run(string[] args) { #if DEBUG Console.WriteLine("Attempting to create IShellItem for file {0}...", args[0]); #endif IShellLink link = (IShellLink) new CShellLink(); //Win32Shell.SHCreateItemFromParsingName(args[0], IntPtr.Zero, Win32Shell.IShellLinkId, out link); IPersistFile persistFileLink = (IPersistFile)link; if (persistFileLink.Load(args[0], 0x00000002L) != 0) { Console.WriteLine("Failed to load via IPersistFile."); return(false); } link.Resolve(IntPtr.Zero, 0); /* * link.SetPath("C:\\Windows\\notepad.exe"); * link.SetArguments(""); */ #if DEBUG Console.WriteLine("Querying for IPropertyStore interface..."); #endif IPropertyStore propStore = (IPropertyStore)link; try { #if DEBUG Console.WriteLine("Attempting to set property 'System.AppUserModel.ID' to {0}...", args[1]); #endif PropertyKey appUserModelKey = new PropertyKey(new Guid("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3"), 5); propStore.SetValue(ref appUserModelKey, new BStrWrapper(args[1])); propStore.Commit(); //Store ((IPersistFile)link).Save(args[0], false); } catch (Exception ex) { #if DEBUG throw; #else Console.WriteLine("Unable to set value of AppUserModel.ID property."); Console.WriteLine(ex); return(false); #endif } return(true); }
public static void HashLnk(string lnkPath) { SHCreateItemFromParsingName(lnkPath, null, typeof(IShellItem2).GUID, out IShellItem item); IShellItem2 item2 = (IShellItem2)item; PSGetPropertyKeyFromName("System.Link.TargetParsingPath", out PropertyKey pk); //PKEY_Link_TargetParsingPath //pk.GUID = new Guid("{B9B4B3FC-2B51-4A42-B5D8-324146AFCF25}"); //pk.PID = 2; string targetPath; try { targetPath = item2.GetString(pk); } catch { targetPath = null; } PSGetPropertyKeyFromName("System.Link.Arguments", out pk); //PKEY_Link_Arguments //pk.GUID = new Guid("{436F2667-14E2-4FEB-B30A-146C53B5B674}"); //pk.PID = 100; string arguments; try { arguments = item2.GetString(pk); } catch { arguments = null; } string blob = GetGeneralizePath(targetPath) + arguments; blob += "do not prehash links. this should only be done by the user.";//特殊但必须存在的字符串 blob = blob.ToLower(); byte[] inBytes = Encoding.Unicode.GetBytes(blob); int byteCount = inBytes.Length; byte[] outBytes = new byte[byteCount]; HashData(inBytes, byteCount, outBytes, byteCount); uint hash = BitConverter.ToUInt32(outBytes, 0); Guid guid = typeof(IPropertyStore).GUID; IPropertyStore store = item2.GetPropertyStore(GPS.READWRITE, ref guid); PSGetPropertyKeyFromName("System.Winx.Hash", out pk); //PKEY_WINX_HASH //pk.GUID = new Guid("{FB8D2D7B-90D1-4E34-BF60-6EAC09922BBF}"); //pk.PID = 2; PropVariant pv = new PropVariant { VarType = VarEnum.VT_UI4, ulVal = hash }; store.SetValue(ref pk, ref pv); store.Commit(); Marshal.ReleaseComObject(store); Marshal.ReleaseComObject(item); PropVariantClear(pv); }
private void InstallShortcut(string shortcutPath, string exePath) { IShellLinkW newShortcut = new IShellLinkW(); // Create a shortcut to the exe newShortcut.SetPath(exePath); // Open the shortcut property store, set the AppUserModelId property IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut; var varAppId = new PROPVARIANT(APP_ID); newShortcutProperties.SetValue(PROPERTYKEY.System.AppUserModel.ID, varAppId); var varToastId = new PROPVARIANT(typeof(NotificationActivator).GUID); newShortcutProperties.SetValue(PROPERTYKEY.System.AppUserModel.ToastActivatorCLSID, varToastId); // Commit the shortcut to disk var newShortcutSave = (IPersistFile)newShortcut; newShortcutSave.Save(shortcutPath, true); }
/// <summary> /// 创建快捷方式 /// </summary> private static void CreatShortcut <T>(string shortcutPath) { String exePath = Process.GetCurrentProcess().MainModule.FileName; IShellLinkW newShortcut = (IShellLinkW) new CShellLink(); ErrorHelper.VerifySucceeded(newShortcut.SetPath(exePath)); IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut; using (PropVariant appId = new PropVariant(_aumid)) { ErrorHelper.VerifySucceeded(newShortcutProperties.SetValue(new PropertyKey(TOAST_G, 5), appId)); } using (PropVariant toastid = new PropVariant(typeof(T).GUID)) { ErrorHelper.VerifySucceeded(newShortcutProperties.SetValue(new PropertyKey(TOAST_G, 26), toastid)); } ErrorHelper.VerifySucceeded(newShortcutProperties.Commit()); // Commit the shortcut to disk IPersistFile newShortcutSave = (IPersistFile)newShortcut; ErrorHelper.VerifySucceeded(newShortcutSave.Save(shortcutPath, true)); }
internal static void SetWindowProperty(IntPtr hwnd, PropertyKey propkey, string value) { // Get the IPropertyStore for the given window handle IPropertyStore propStore = GetWindowPropertyStore(hwnd); // Set the value PropVariant pv = new PropVariant(); propStore.SetValue(ref propkey, ref pv); // Dispose the IPropertyStore and PropVariant Marshal.ReleaseComObject(propStore); pv.Clear(); }
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 Exception("Unable to get writable property store for this property.", Marshal.GetExceptionForHR(hr)); } HResult result = writablePropStore.SetValue(ref propertyKey, propVar); if (!AllowSetTruncatedValue && (int)result == ShellNativeMethods.InPlaceStringTruncated) { throw new ArgumentOutOfRangeException("propVar", "A value had to be truncated in a string or rounded if a numeric value. Set AllowTruncatedValue to true to prevent this exception."); } if (!CoreErrorHelper.Succeeded(result)) { throw new Exception("Unable to set property.", Marshal.GetExceptionForHR((int)result)); } writablePropStore.Commit(); } catch (InvalidComObjectException e) { throw new Exception("Unable to get writable property store for this property.", e); } catch (InvalidCastException) { throw new Exception("Unable to get writable property store for this property."); } finally { if (writablePropStore != null) { Marshal.ReleaseComObject(writablePropStore); writablePropStore = null; } } }
public void SetValue(KeyValuePair <PropertyKey, PropVariant> value) { if (Contains(value.Key)) { var key = value.Key; var propValue = value.Value; HResult.Try(_propertyStoreInterface.SetValue(ref key, ref propValue)); propValue.Dispose(); } else { throw new KeyNotFoundException(String.Format("The specified key ({0}) was not found.", value.Key.ToString())); } }
public void create(string shortcutPath = "") { if (!string.IsNullOrEmpty(shortcutPath)) { if (!shortcutPath.Contains("\\")) { this.ShortcutPath = this.generateLinkPath(shortcutPath); } else { this.ShortcutPath = shortcutPath; } } if (string.IsNullOrEmpty(this.ShortcutPath)) { this.ShortcutPath = this.generateDefaultLinkPath(); } string folderPath = Path.GetDirectoryName(this.ShortcutPath); if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } // Find the path to the current executable IShellLinkW newShortcut = (IShellLinkW) new CShellLink(); // Create a shortcut to the exe ResultChecker.VerifyAndThrow("SetPath", newShortcut.SetPath(this.ExePath)); ResultChecker.VerifyAndThrow("SetArguments", newShortcut.SetArguments(this.Arguments)); // Open the shortcut property store, set the AppUserModelId property IPropertyStore newShortcutProperties = (IPropertyStore)newShortcut; if (!string.IsNullOrEmpty(this.AppUserModelID)) { using (PropVariant appId = new PropVariant(this.AppUserModelID)) { ResultChecker.VerifyAndThrow("SetValue", newShortcutProperties.SetValue(SystemProperties.System.AppUserModel.ID, appId)); ResultChecker.VerifyAndThrow("Commit", newShortcutProperties.Commit()); } } // Commit the shortcut to disk IPersistFile newShortcutSave = (IPersistFile)newShortcut; ResultChecker.VerifyAndThrow("Save", newShortcutSave.Save(this.ShortcutPath, true)); }
/// <summary> /// Creates a shortcut to enable the app to receive toast notifications. /// </summary> /// <remarks> /// Documentation: https://docs.microsoft.com/en-us/windows/win32/shell/enable-desktop-toast-with-appusermodelid /// </remarks> /// <param name="shortcutPath">Full path to the shortcut (including .lnk), must be in Program Files or Start Menu</param> /// <param name="appExecutablePath">Path the to app that receives notifications</param> /// <param name="arguments">Optional arguments</param> /// <param name="appName">The name of the app - used to create the toast</param> /// <param name="activatorId">The activation id</param> public static void RegisterAppForNotifications(string shortcutPath, string appExecutablePath, string arguments, string appName, string activatorId) { var shellLinkClass = new ShellLinkCoClass(); IShellLinkW shellLink = (IShellLinkW)shellLinkClass; shellLink.SetPath(appExecutablePath); IPropertyStore propertyStore = (IPropertyStore)shellLinkClass; IPersistFile persistFile = (IPersistFile)shellLinkClass; if (arguments != null) { shellLink.SetArguments(arguments); } // https://docs.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-id propertyStore.SetValue(new PropertyKey("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3", 5), new PROPVARIANT(appName)); // https://docs.microsoft.com/en-us/windows/win32/properties/props-system-appusermodel-toastactivatorclsid propertyStore.SetValue(new PropertyKey("9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3", 26), new PROPVARIANT(new Guid(activatorId))); propertyStore.Commit(); persistFile.Save(shortcutPath, true); }
/// <summary> /// Sets property value of the property /// </summary> /// <returns>Property value</returns> public void SetValue(PropertyKey key, object value) { ComThread.Assert(); if (Mode == AccessMode.Read) { return; } if (!Contains(key)) { return; } Marshal.ThrowExceptionForHR(_propertyStoreInteface.SetValue(ref key, ref value)); _propertyStoreInteface.Commit(); }
private static void SetProperty(IntPtr hwnd, PropertyKey key, PropVariant value) { IPropertyStore propStore = null; try { propStore = GetWindowPropertyStore(hwnd); propStore.SetValue(ref key, value); propStore.Commit(); } finally { if (propStore != null) { Marshal.ReleaseComObject(propStore); } } }
internal 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); }