检测应用程序是否固定到任务栏

时间:2017-02-27 04:55:49

标签: c# wpf windows taskbar

我有一个C#/ WPF应用程序,我想根据它是否是从Windows任务栏上的固定链接启动而给出不同的行为。

  1. 有没有办法检测我的应用程序是否已固定到任务栏?
  2. 有没有办法检测我的应用程序是否已从任务栏上的固定项启动?

1 个答案:

答案 0 :(得分:4)

您可以通过检查文件夹%appdata%\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar来检测应用程序是否固定到当前用户的任务栏,其中存储了所有固定应用程序的快捷方式。例如(需要添加对Windows脚本宿主对象模型的COM引用):

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的快捷方式,因此使用所有这些信息可以轻松检查应用程序是否从任务栏启动。

相关问题