《Windows脚本编程核心技术精解Chapter09.pdf》由会员分享,可在线阅读,更多相关《Windows脚本编程核心技术精解Chapter09.pdf(32页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、Chapter 9Mastering LinksIn This Chapter?Learn more about the power of shortcut files?Createand modify shortcut files by script?Search for invalid links and duplicating keyboard shortcuts?Change shortcut icons dynamically?Preselect a shortcuts window size?Use the hidden Shell Linkobject to resolve br
2、oken links?Discover the undocumented link resolving mechanism and the new Windows 2000 Distributed Link Tracking Service?Open a shortcut targets Properties page?Mark a shortcut target file in the ExplorerNow that you know how to handle your file system,take a look atlink files.In this chapter,you le
3、arn what link files are and how touse them to customize menus.You also learn how to create new linkfiles from scratch and how to check existing link files for errors.Usingsecret API functions,you can even automatically repair broken link files.Why Do I Need Links Anyway?Links are small but extremely
4、 powerful files.They represent files,folders,and system objects located somewhere else.Links build the foundation ofcustomizing Windows.Links make the Programs menu work.To see howimportant links really are,start a search for*.LNK.Scripts can use links to place themselves in important places.You can
5、 add your script to the Start menu,place it into the Send To folder,or insert a reference into the Startup folder.In addition,scripts can use their link functions for maintenance.Scripts can search for links,checkwhether their destinations are still valid,and sort out any broken links.4684-8 ch09.f.
6、qc 3/3/00 9:35 AM Page 289More importantly,scripts can check the internal keyboard shortcuts and makesure there are no duplicate entries.Windows doesnt check for this,allowingyou to assign multiple keyboard shortcuts to more than one link file,or even to override important built-in Windows shortcuts
7、resulting in erroneousbehavior.By using some undocumented Windows magic,you can even resolve brokenlinks and mark files and folders.Creating a new link fileThe WScript.Shellobject contains all the methods needed for managinglinks.The following example asks for a name and places a shortcut to theWind
8、ows editor right on your desktop:9-1.VBSset wshshell=CreateObject(“WScript.Shell”)desktop=wshshell.SpecialFolders(“desktop”)linkname=InputBox(“What do you want to call your new link?”,_,”Windows Editor”)target=“notepad.exe”linkname=desktop&“”&linkname&“.lnk”create new shortcut objectset scut=wshshel
9、l.CreateShortcut(linkname)fill in informationscut.TargetPath=target save shortcut objectscut.SaveMsgBox“Done-new shortcut on your desktop!”Take a look at your desktop.The script adds a new shortcut and,when youopen it,launches the editor.Examining the shortcut objectAll this magic was done with the
10、help of a shortcut object.A shortcut objectrepresents the internal properties of a link file.CreateShortcutis yoursecret key to the shortcut object.It always returns a shortcut object.If youspecified a link file that doesnt yet exist,the new shortcut object is empty.However,you can easily access the
11、 hidden properties of existing shortcuts.Just specify an existing shortcut file path.290Part II:Conquering the File SystemII4684-8 ch09.f.qc 3/3/00 9:35 AM Page 290CreateShortcutwill fail if the specified file name doesnt carry the.linkfile extension.The resulting shortcut object is not the actual s
12、hortcut.Itsjust an information object stored somewhere in memory.To write theproperties of the shortcut object back to the actual shortcut file,you mustcall the objects Savemethod.Table 9-1 shows how shortcut objects are organized.Table 9-1The Shortcut ObjectProperty/MethodDescriptionProperty Argume
13、nts As StringAdditional command-line argumentsyou want to pass to the target fileProperty Description As StringOptional descriptive informationabout what this shortcut is used forProperty FullName As StringFull path name of the link file(undocumented)Property Hotkey As StringKeyboard shortcutPropert
14、y IconLocation Display icon of the shortcutAs StringProperty RelativePath Not fully supported(undocumented)As StringSub SaveSaves the information to theshortcutProperty TargetPath As StringPath name of the shortcut target fileProperty WindowStyle As LongType of window the shortcut should openPropert
15、y WorkingDirectory Initial directory settingAs StringAccessing Existing Link FilesCreateShortcutis somewhat misleading,as it doesnt create a shortcut file.It creates a shortcut object.You can easily manage existing link files usingCreateShortcutand reveal their internal properties.Searching for inva
16、lid linksThe next script checks your entire Programs menu and reports any invalidlinks.Figure 9-1 shows the result.Chapter 9:Mastering Links291II4684-8 ch09.f.qc 3/3/00 9:35 AM Page 291For your convenience,the script offers to delete invalid links.Before youdelete something,always think twice.Shortc
17、ut targets on network drives ortargets to disk drives may not currently be available but may still be useful.Check the message dialog box carefully before you decide to clean up yourPrograms menu!9-2.VBSset wshshell=CreateObject(“WScript.Shell”)set fs=CreateObject(“Scripting.FileSystemObject”)global
18、 variablesnum_checked=0num_error=0num_deleted=0programs=wshshell.SpecialFolders(“programs”)set folderobj=fs.GetFolder(programs)CheckFolder folderobjmsg=“I have checked“&num_checked&“links.”&vbCrmsg=msg&“I found“&num_error&“invalid links.”&vbCrmsg=msg&“You asked me to delete“&num_deleted&“links”MsgBo
19、x msg,vbInformationsub CheckFolder(folderobj)for each file in folderobj.filesext=lcase(fs.GetExtensionName(file.name)if ext=“lnk”thennum_checked=num_checked+1set scut=wshshell.CreateShortcut(file.path)target=scut.TargetPathif not fs.FileExists(target)thennum_error=num_error+1msg=“Link“”&file.path&“”
20、points to“”_&target&“”&vbCrmsg=msg&“The target no longer exists!Do“_&“you want to delete the link?”response=MsgBox(msg,vbQuestion+vbYesNo _+vbDefaultButton2)if response=vbYes thennum_deleted=num_deleted+1file.deleteend ifend ifend ifnextfor each subfolder in folderobj.subfoldersCheckFolder subfolder
21、nextend sub292Part II:Conquering the File SystemII4684-8 ch09.f.qc 3/3/00 9:35 AM Page 292Figure 9-1:Check for invalid and outdated links in your Programs menu.Finding(and eliminating)duplicate keyboard shortcutsKeyboard shortcuts are extremely usefulafter all,any shortcut file with akeyboard shortc
22、ut can be invoked just by pressing the keys you specify.Justright-click on a link file and choose Properties.Then enter your keyboardshortcut in the shortcut text field and click OK.But,this doesnt always work!Keyboard shortcuts can launch files only if the shortcut is located either onyour desktop
23、or inside the Programs menu.These are the only places Windowslooks for keyboard shortcuts.It would just take much too long to check all linkfiles anywhere in the file system.One of the most annoying reasons for failure is duplicate shortcut keys.Windowsdoesnt make any effort to prevent you from assi
24、gning new keyboard shortcutsthat are already in use by some other link file.Once you have multiple link filesusing the same key combination,its up to Windows which file will be launched.Even worse,its possible to override Windows internal shortcuts.If youassign F1 to a link file,this key will no lon
25、ger invoke Windows help.Its very hard to resolve duplicate keyboard shortcuts because Windows cantlist the shortcuts in use.You would have to open the Properties page of eachand every link file manually to look for shortcuts.Thats too much work.Thefollowing script creates a shortcut list automatical
26、ly and presents the result asan HTML file similar to the one shown in Figure 9-2.9-3.VBSset wshshell=CreateObject(“WScript.Shell”)set fs=CreateObject(“Scripting.FileSystemObject”)startmenu=wshshell.SpecialFolders(“startmenu”)desktop=wshshell.SpecialFolders(“desktop”)outputfile=“C:LINKLIST.HTM”dim li
27、nks(1000,1)counter=0Chapter 9:Mastering Links293II4684-8 ch09.f.qc 3/3/00 9:35 AM Page 293CheckFolder fs.GetFolder(desktop),falseCheckFolder fs.GetFolder(startmenu),truefor x=0 to counter-1for y=x+1 to counter-2if links(x,1)links(y,1)thentemp=links(x,1)links(x,1)=links(y,1)links(y,1)=temptemp=links(
28、x,0)links(x,0)=links(y,0)links(y,0)=tempend ifnextnextset output=fs.CreateTextFile(outputfile,true)output.WriteLine“”output.WriteLine“List of Shortcut Hotkeys”output.WriteLine“”&counter&“hotkeys found.”output.WriteLine“”for x=0 to counter-1output.WriteLine“”&links(x,1)&“”_&links(x,0)&“”nextoutput.Wr
29、iteLine“”output.closewshshell.run“iexplore.exe“&outputfilesub CheckFolder(folderobj,subdirs)for each file in folderobj.filesext=lcase(fs.GetExtensionName(file.name)if ext=“lnk”thenset scut=wshshell.CreateShortcut(file.path)hotkey=scut.HotKeyif not(hotkey=”or hotkey=”!”)thenlinks(counter,0)=file.path
30、links(counter,1)=hotkeycounter=counter+1end ifend ifnextif subdirs thenfor each subfolder in folderobj.subfoldersCheckFolder subfolder,subdirsnextend ifend sub294Part II:Conquering the File SystemII4684-8 ch09.f.qc 3/3/00 9:35 AM Page 294A bubble-like algorithm sorts the keyboard shortcuts,so duplic
31、ate entriesare easy to recognize.Note that this script searches for links only on thedesktop and inside the Start menu,as these are the only places wherekeyboard shortcuts work.Figure 9-2:Build a list of keyboard shortcuts and find duplicate entries.The script searches recursively only in the Start
32、menu.Subfolders on thedesktop wont be searched.Undefined HotKey entries return either an empty string or“!”.Some specialcharacters such as“”will not be shown by the HotKey property.Instead,you only see the modifier keys.Take a look at the files Properties page to see the actual shortcut key.To elimi
33、nate duplicate shortcuts,just open the Properties page and deletethe shortcut entry.Changing a Shortcut IconBy default,Windows uses the file that the TargetPathproperty points to asan icon resource.You dont need to accept this default.Just specify your ownicon file as IconLocationproperty.This is es
34、pecially useful if you plan toinsert scripts into the Start menu or the Send To folder.Where do you get icons to choose from?The Windows system folder is filledwith icon resources you can use.Or,you can create your very own personalicons!Its all possible.Borrowing system iconsSystem icons hide in fi
35、les like shell32.dllor moricons.dll.To specify anicon,supply IconLocationwith the filename and icon index:for example,shell32.dll,2.Chapter 9:Mastering Links295II4684-8 ch09.f.qc 3/3/00 9:35 AM Page 295How do you know which files to pick,though?Not every file is a good iconresource,but Ive prepared
36、many icon tools for you.You can get a head startby jumping to Chapter 22.Or use the following scriptit uses the ListViewcontrol along with the Icon Picker dialog box,both of which you created inChapter 6.Make sure you install both installlistviewsetup.exeandinstalliconpicksetup.exefrom the companion
37、 CD before you launchscript 9-4.vbs.This script automatically changes the icon of any link file.Drag a link file ontothe script icon.It may take some seconds for the script to search for available icons.Be patient,have cup of coffee,and relax.Your reward is a huge list of available icons.It willprov
38、ide you with many more choices than the official dialog box could ever offer.First,the script searches both your Windows folder and the system folder for files that contain at least three icons.This can take some seconds.Next,it displays all icon files as shown in Figure 9-3 so you can select one.Th
39、e IconPicker dialog box then displays the icons stored in the selected file.Figure 9-4shows the result.Choose an icon,or choose Cancel to select a different icon file.Figure 9-3:A ListView lists all the icon files available on your system.9-4.VBSset fs=CreateObject(“Scripting.FileSystemObject”)any a
40、rguments supplied?set args=WScript.Argumentsif args.Count=0 thenMsgBox“Drag a link file on my icon to see me at work!”WScript.Quitelseif lcase(fs.GetExtensionName(args(0)”lnk”then296Part II:Conquering the File SystemII4684-8 ch09.f.qc 3/3/00 9:35 AM Page 296MsgBox“I only accept link files(shortcuts)
41、!”WScript.Quitend if access COM objects:set iconpick=CreateObject(“iconpicker.tool”)set lview=CreateObject(“listview.tool”)set wshshell=CreateObject(“WScript.Shell”)find out icon library folders:set windir=fs.GetSpecialFolder(0)set sysdir=fs.GetSpecialFolder(1)initialize list view:lview.width=600lvi
42、ew.height=400lview.AddHeader“Icons available”,30lview.AddHeader“Icon Library”,70lview.MultiEdit=true build list of available iconsPopulateList windirPopulateList sysdir Sort by icon count:lview.Sort 1,1do Select Icon Lib:set result=lview.Show(“Extended Information:“&name)if result.Count0 then extrac
43、t library file namelib=Split(result(1),vbCrLf)libname=lib(0)elselibname=“”end if library selected?good:if not libname=”then show icons in library:icon=iconpick.PickIcon(libname)end if loop until either icon is chosen or library selection was cancelled:loop until libname=“”or not icon=”did user selec
44、t an icon?if not icon=”then yes:access selected shortcut:set scut=wshshell.CreateShortcut(args(0)Chapter 9:Mastering Links297II4684-8 ch09.f.qc 3/3/00 9:35 AM Page 297 change icon and save informationscut.IconLocation=iconscut.SaveMsgBox“Changed link file icon!”elseMsgBox“You did not specify an icon
45、.”end ifsub PopulateList(folderobj)search for icon files in entire folderfor each file in folderobj.files how many icons are stored in file?iconcount=iconpick.CountIcons(file.path)if iconcount2 then pad icon count with spaces so sorting as string worksiconcount=right(space(10)&iconcount,10)lview.Add
46、Item file.namelview.AddSubItem 1,iconcountend ifnextend subFigure 9-4:The Icon Picker dialog box lists the icons available.Once you have selected an icon,the script changes the shortcutsIconLocationproperty to the selected icon.Figure 9-5 shows the finalresult:Your shortcut file has changed its icon
47、!This script will only work if you have properly registered both the Listviewtool and the icon picker tool.You can find convenient setup.exepackagesfor both tools on the companion CD.Should you receive“Cant create object”error messages,install both setup.exefiles:installlistviewsetup.exeand installi
48、conpicksetup.exe.298Part II:Conquering the File SystemII4684-8 ch09.f.qc 3/3/00 9:35 AM Page 298Depending on the number of files in your Windows and system folders,it maytake up to a minute for the script to collect all icon files.Be a little patient!InChapter 22,I present a way to conserve the list
49、 of icon files in a text file.Thisway,you can open the icon library list much more rapidly.Figure 9-5:Your shortcut object has received a new icon.Note also that the icon index depends on the Windows version you use.TheIcon index is a simple counter that selects the icon based on its position inside
50、the icon file.Microsoft changes the icon order frequently,so the same indexnumber may select different icons on different Windows versions.Aside from the icon index,there are fixed icon resource identifiers.They dontchange with Windows versions,because they uniquely identify a specific icon.Resource