2017-02-27 38 views
1

我有一个C#/ WPF应用程序,我想给它不同的行为,具体取决于它是否已从Windows任务栏上的固定链接启动。检测应用程序是否被固定到任务栏

  1. 有没有一种方法来检测我的应用程序是否已经固定到任务栏?
  2. 有没有办法检测我的应用程序是否从任务栏上的固定项目开始?
+0

https://www.codeproject.com/Articles/43768/Windows-Taskbar-Check-if-a-program-or-window-is –

回答

3

您可以通过检查文件夹%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,所以这一切的信息可以很容易地检查,如果应用程序是从开始任务栏或不。

+0

很好的答案,谢谢! –

相关问题