在CSDN论坛看到有网友提问如何把程序钉到Windows7的任务栏,ccrun(妖哥)对这个问题很感兴趣,于是google了一下,没有找到相关的API资料,但是在国外的一个站点看到用FolderItemVerb对象来实现的方法,关于具体的资料,可以查阅MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/bb774172(v=vs.85).aspx
在Delphi中实现的代码如下。编译环境:Delphi7和XE2,测试操作系统为中文和英文Windows7
uses ComObj; procedure CrnPinAppToWin7Taskbar(strPath, strApp: string);
var
vShell, vFolder, vFolderItem, vItemVerbs: Variant;
vPath, vApp: Variant;
i: Integer;
str: String;
h: HINST;
szPinName: array[..] of Char;
begin
vShell := CreateOleObject('Shell.Application');
vPath := strPath;
vFolder := vShell.NameSpace(vPath);
vApp := strApp;
vFolderItem := vFolder.ParseName(vApp);
vItemVerbs := vFolderItem.Verbs; h := LoadLibrary('Shell32.dll');
LoadString(h, , szPinName, );
FreeLibrary(h); for i := to vItemVerbs.Count do
begin
str := vItemVerbs.Item(i).Name; if SameText(str, szPinName) then
begin
// 63 63 72 75 6E 2E 63 6F 6D
vItemVerbs.Item(i).DoIt;
end;
end;
end; procedure TForm1.Button1Click(Sender: TObject);
begin
CrnPinAppToWin7Taskbar('C:\windows', 'regedit.exe');
end;
在C++Builder中的实现代码如下。编译环境:C++Builder6和XE2,测试操作系统:中文和英文Windows7
#include <comobj.hpp> void __fastcall CrnPinAppToWin7Taskbar(String strPath, String strApp)
{
Variant vShell = CreateOleObject("Shell.Application");
Variant vFolder = vShell.OleFunction("NameSpace", WideString(strPath));
Variant vFolderItem = vFolder.OleFunction("ParseName", WideString(strApp));
Variant vItemVerbs = vFolderItem.OleFunction("Verbs"); // 获取Pin to Taskbar的Verb字符串, 感谢titilima
HINSTANCE hInst = ::LoadLibrary(TEXT("Shell32.dll")); TCHAR szPinName[] = { };
::LoadString(hInst, , szPinName, ); ::FreeLibrary(hInst); String str; int nCount = vItemVerbs.OlePropertyGet("Count");
for (int i = ; i < nCount; i++)
{
str = vItemVerbs.OleFunction("Item", i).OlePropertyGet("Name"); if (SameText(str, szPinName))
{
// 63 63 72 75 6E 2E 63 6F 6D
vItemVerbs.OleFunction("Item", i).OleFunction("DoIt");
}
}
} void __fastcall TForm1::Button1Click(TObject *Sender)
{
CrnPinAppToWin7Taskbar("C:\\windows\\", "notepad.exe");
}
另外,感谢titilima大牛,针对.lnk文件钉到Win7任务栏,有更简便的方法:
C++代码:
::ShellExecute(NULL, TEXT("TaskbarPin"), TEXT("E:\\Temp\\Notepad.lnk"), NULL, NULL, SW_SHOW);
Delphi代码:
ShellExecute(nil, 'TaskbarPin', 'E:\Temp\Notepad.lnk'), nil, nil, SW_SHOW);