我有一个C#/ WPF应用程序,我想给不同的行为取决于它是否已经从Windows任务栏上的固定链接开始。
您可以通过检查文件夹%appdata%\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar
任务栏来检测应用程序是否固定到当前用户的任务栏,其中存储所有固定应用程序的快捷方式。 例如(需要将COM引用添加到Windows脚本宿主对象模型):
private static bool IsCurrentApplicationPinned() { // path to current executable var currentPath = Assembly.GetEntryAssembly().Location; // folder with shortcuts string location = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar"); if (!Directory.Exists(location)) return false; foreach (var file in Directory.GetFiles(location, "*.lnk")) { IWshShell shell = new WshShell(); var lnk = shell.CreateShortcut(file) as IWshShortcut; if (lnk != null) { // if there is shortcut pointing to current executable - it's pinned if (String.Equals(lnk.TargetPath, currentPath, StringComparison.InvariantCultureIgnoreCase)) { return true; } } } return false; }
还有一种方法可以检测应用程序是否从固定项目启动。 为此,您将需要GetStartupInfo
win api函数。 在其他信息中,它将为您提供一个完整的路径到当前进程的快捷方式(或只是文件)。 例:
[DllImport("kernel32.dll", SetLastError = true, EntryPoint = "GetStartupInfoA")] public static extern void GetStartupInfo(out STARTUPINFO lpStartupInfo); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] public struct STARTUPINFO { public uint cb; public string lpReserved; public string lpDesktop; public string lpTitle; public uint dwX; public uint dwY; public uint dwXSize; public uint dwYSize; public uint dwXCountChars; public uint dwYCountChars; public uint dwFillAttribute; public uint dwFlags; public ushort wShowWindow; public ushort cbReserved2; public IntPtr lpReserved2; public IntPtr hStdInput; public IntPtr hStdOutput; public IntPtr hStdError; }
用法:
STARTUPINFO startInfo; GetStartupInfo(out startInfo); var startupPath = startInfo.lpTitle;
现在,如果您已经从任务栏启动应用程序, startupPath
将指向%appdata%\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar
的快捷方式,因此使用所有这些信息很容易检查应用程序是否从任务栏启动。