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

4

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

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

https://www.codeproject.com/Articles/43768/Windows-Taskbar-Check-if-a-program-or-window-is - Dirty Developer
1个回答

6

您可以通过检查文件夹%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创建的快捷方式,因此有了所有这些信息,很容易检查应用程序是否是从任务栏启动的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接