2017-02-27 35 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

很好的答案,謝謝! –

相關問題