Объект Shell
Автор: А. Климов
Русский проект: Visual Basic на русском
Опубликовано: 30.05.2002
Исправлено: 13.03.2005
Версия текста: 1.1
Объект Microsoft Windows Shell позволяет получить доступ к различным настройкам Windows при помощи технологий COM и Automation, что позволяет использовать Visual Basic и VBScript. Например, вы можете получить доступ к различным диалоговым окнам, к файловой системе, запускать программы и изменять системные настройки. Итак, знакомимся с объектом Shell.
Версия Shell
Многие из объектов оболочки Shell доступны начиная с версии 4.71, но существуют и объекты доступные только в версии 5.00 и выше. Версия 4.71 установлена на компьютерах с Windows 98, а версия 5.00 на Windows 2000. Ниже приводится список доступных объектов для каждой версии (версия 5.0 поддерживает все объекты версии 4.71).
Версия 4.71 | Версия 5.00 |
---|---|
Folder | DIDiskQuotaUser |
FolderItemVerb | DiskQuotaControl |
FolderItemVerbs | Folder2 |
Shell | FolderItem |
ShellFolderView | FolderItems |
ShellUIHelper | FolderItems2 |
ShellWindows | IShellDispatch2 |
WebViewFolderContents | IShellLinkDual2 |
ShellFolderItem | |
ShellFolderViewOC | |
ShellLinkObject |
Доступ к объекту Shell
Раннее связывание
Получить доступ к объекту Shell в Visual Basic можно при помощи раннего связывания, добавив ссылку к библиотекам:
- Microsoft Internet Controls (SHDOCVW.DLL)
- Microsoft Shell Controls and Automation (SHDOC401.DLL)
Откроем проект в Visual Basic. Добавим ссылки к библиотекам и пишем следующий код для кнопки Command1
Данный пример сворачивает все открытые окна
Позднее связывание
Также можно получить доступ к объектам Shell при помощи позднего связывания. Этот способ используется в скриптовых языках.
Приведем пример использования объекта Shell в VBScript.
Аналогично работает этот код и в Visual Basic
Примечание: Не все объекты Shell доступны при помощи позднего связывания. Вот список недоступных объектов
- DiskQuotaControl
- ShellFolderView
- ShellFolderViewOC
- ShellUIHelper
- WebViewFolderContents
Эти ограничения не являются проблемой для Visual Basic, где вы можете получить доступ через ссылки к соответствующим библиотекам, как это было описано немного выше. Но в скриптовых языках вроде VBScript у вас такой возможности нет.
HTML-элемент OBJECT
Вы также можете получить доступ к объектам Shell на html-страничке, используя элемент OBJECT. Для этого необходимо связать атрибут идентификатора ID элемента OBJECT с некоторым именем и идентифицировать объект с его регистрационным номером в системе (CLASSID). Следующий пример создает экземпляр объекта ShellFolderItem при помощи OBJECT
Список объектов Shell и их CLASSID
Object | CLASSID |
---|---|
DIDiskQuotaUser | 7988B571-EC89-11cf-9C00-00AA00A14F56 |
DiskQuotaControl | 7988B571-EC89-11cf-9C00-00AA00A14F56 |
Folder | BBCBDE60-C3FF-11CE-8350-444553540000 |
Folder2 | F0d2d8ef-3890-11d2-Bf8b-00c04fb93661 |
FolderItem | 744129E0-CBE5-11CE-8350-444553540000 |
FolderItems | 744129E0-CBE5-11CE-8350-444553540000 |
FolderItems2 | C94F0AD0-F363-11d2-A327-00C04F8EEC7F |
FolderItemVerb | 08EC3E00-50B0-11CF-960C-0080C7F4EE85 |
FolderItemVerbs | 1F8352C0-50B0-11CF-960C-0080C7F4EE85 |
IShellDispatch2 | A4C6892C-3BA9-11d2-9DEA-00C04FB16162 |
IShellLinkDual2 | 317EE249-F12E-11d2-B1E4-00C04F8EEB3E |
Shell | 13709620-C279-11CE-A49E-444553540000 |
ShellFolderItem | 2fe352ea-fd1f-11d2-b1f4-00c04f8eeb3e |
ShellFolderView | 62112AA1-EBE4-11cf-A5FB-0020AFE7292D |
ShellFolderViewOC | 4a3df050-23bd-11d2-939f-00a0c91eedba |
ShellLinkObject | 11219420-1768-11d1-95BE-00609797EA4F |
ShellUIHelper | 64AB4BB7-111E-11D1-8F79-00C04FC2FBE1 |
ShellWindows | 9BA05972-F6A8-11CF-A442-00A0C90A8F39 |
WebViewFolderContents | 1820FED0-473E-11D0-A96C-00C04FD705A2 |
Объект Shell
Объект Shell является очень мощным оружием программиста для доступа ко многим возможностям Windows Shell. Вы сможете:
- Открывать, просматривать и перемещаться по папкам
- Сворачивать, восстанавливать окна. А также располагать их в каскадном или другом порядке
- Запускать апплеты Панели управления
- Показывать системные диалоговые окна
Приведем пример использования многих методов объектов Shell на Visual Basic
Откройте проект, установите ссылки на библиотеки, добавьте на форму элемент ListBox
Теперь примеры при помощи HTML.
В case 6 и case 8 использовались пути (имена папок) для английской версии Windows98. В случае необходимости используйте константы ShellSpecialFolderConstants, позволяющие получить реальные пути к системным каталогам.
Эпилог
Данная статья предоставляет лишь краткий обзор богатых возможностей, предоставляемых объектом Shell. Читайте MSDN, где достаточно подробно описана документация по Shell. Также, в Visual Basic вы можете просмотреть свойства, методы и объекты, предоставляемые Shell при помощи Object Browser (View-Object Browser или F2). Напоследок, приведу пример вызова диалогового окна Добавление в избранное
Scriptable Shell Objects
The Windows Shell provides a powerful set of automation objects that enable you to program the Shell with Microsoft Visual Basic and scripting languages such as Microsoft JScript (compatible with ECMA 262 language specification) and Microsoft Visual Basic Scripting Edition (VBScript). You can use these objects to access many of the Shell’s features and dialog boxes. For example, you can access the file system, launch programs, and change system settings.
This section introduces the scriptable Shell objects.
- Shell Versions
- Instantiating Shell Objects
- Late Binding
- HTML OBJECT Element
- Shell Object
- Security
- Folder Objects
Shell Versions
Many of the Shell objects became available in version 4.71 of the Shell. Others are available in version 5.00 and later. Version 5.00 became available with WindowsВ 2000. The following table lists each Shell object under the version of the Shell in which the object became available.
Version 4.71 | Version 5.00 |
---|---|
Folder | DIDiskQuotaUser |
FolderItemVerb | DiskQuotaControl |
FolderItemVerbs | Folder2 |
Shell | FolderItem |
ShellFolderView | FolderItems |
ShellUIHelper | FolderItems2 |
ShellWindows | IShellDispatch2 |
WebViewFolderContents | IShellLinkDual2 |
ShellFolderItem | |
ShellFolderViewOC | |
ShellLinkObject |
Instantiating Shell Objects
To instantiate the Shell objects in Visual Basic applications with early binding, add references to the following libraries in your project:
- Microsoft Internet Controls (SHDocVw)
- Microsoft Shell Controls and Automation (Shell32)
Late Binding
You can also instantiate many of the Shell objects with late binding. This approach works in Visual Basic applications and in script. The following example shows how to instantiate the Shell object in JScript.
The following example shows how to instantiate the Folder object in VBScript.
In the preceding example, sDir is the path to the Folder object. Note that the ShellSpecialFolderConstants enumeration values are not available in script.
The ProgID for each of the Shell objects is shown in the following table.
Object | ProgID |
---|---|
DIDiskQuotaUser | Microsoft.DiskQuota.1 |
DiskQuotaControl | Cannot late bind |
Folder | shell.Shell_Application.NameSpace(«. «) |
Folder2 | shell.Shell_Application.NameSpace(«. «) |
FolderItem | shell.Shell_Application.NameSpace(«. «).Self or Folder.Items.Item or Folder.ParseName |
FolderItems | Folder.Items |
FolderItems2 | Folder.Items |
FolderItemVerb | Shell.NameSpace(«. «).Self.Verbs.Item() |
FolderItemVerbs | FolderItem.Verbs or Shell.NameSpace(«. «).Self.Verbs |
IShellDispatch2 | shell.Shell_Application |
IShellLinkDual2 | Shell.NameSpace(«. «).Self.GetLink or Shell.NameSpace(«. «).Items().GetLink |
Shell | shell.Shell_Application |
ShellFolderItem | Shell.NameSpace(«. «).Self or Shell.NameSpace(«. «).Items() |
ShellFolderView | Cannot late bind |
ShellFolderViewOC | Cannot late bind |
ShellLinkObject | Shell.NameSpace(«. «).Self.GetLink or Shell.NameSpace(«. «).Items().GetLink |
ShellUIHelper | Cannot late bind |
ShellWindows | shell.Shell_Windows or ShellWindows._NewEnum |
WebViewFolderContents | Cannot late bind |
HTML OBJECT Element
You can also use the OBJECT element to instantiate Shell objects on an HTML page. To do this, set the OBJECT element’s ID attribute to the variable name you will use in your scripts, and identify the object using its registered number (CLASSID). The following HTML creates an instance of the ShellFolderItem object using the OBJECT element.
The following table lists each Shell object and its respective CLASSID.
DIDiskQuotaUser | 7988B571-EC89-11cf-9C00-00AA00A14F56 |
DiskQuotaControl | 7988B571-EC89-11cf-9C00-00AA00A14F56 |
Folder | BBCBDE60-C3FF-11CE-8350-444553540000 |
Folder2 | f0d2d8ef-3890-11d2-bf8b-00c04fb93661 |
FolderItem | 744129E0-CBE5-11CE-8350-444553540000 |
FolderItems | 744129E0-CBE5-11CE-8350-444553540000 |
FolderItems2 | C94F0AD0-F363-11d2-A327-00C04F8EEC7F |
FolderItemVerb | 08EC3E00-50B0-11CF-960C-0080C7F4EE85 |
FolderItemVerbs | 1F8352C0-50B0-11CF-960C-0080C7F4EE85 |
IShellDispatch2 | A4C6892C-3BA9-11d2-9DEA-00C04FB16162 |
IShellLinkDual2 | 317EE249-F12E-11d2-B1E4-00C04F8EEB3E |
Shell | 13709620-C279-11CE-A49E-444553540000 |
ShellFolderItem | 2fe352ea-fd1f-11d2-b1f4-00c04f8eeb3e |
ShellFolderView | 62112AA1-EBE4-11cf-A5FB-0020AFE7292D |
ShellFolderViewOC | 4a3df050-23bd-11d2-939f-00a0c91eedba |
ShellLinkObject | 11219420-1768-11d1-95BE-00609797EA4F |
ShellUIHelper | 64AB4BB7-111E-11D1-8F79-00C04FC2FBE1 |
ShellWindows | 9BA05972-F6A8-11CF-A442-00A0C90A8F39 |
WebViewFolderContents | 1820FED0-473E-11D0-A96C-00C04FD705A2 |
Shell Object
The Shell object represents the objects in the Shell. You can use the methods exposed by the Shell object to:
- Open, explore, and browse for folders.
- Minimize, restore, cascade, or tile open windows.
- Launch Control Panel applications.
- Display system dialog boxes.
Users are perhaps most familiar with the commands they access from the Start menu and the taskbar’s shortcut menu. The taskbar’s shortcut menu appears when users right-click the taskbar. The following HTML Application (HTA) produces a start page with buttons that implement many of the Shell object’s methods. Some of these methods implement features on the Start menu and the taskbar’s shortcut menu.
Security
As an application, an HTA runs under a different security model than a webpage. To interact with a webpage that implements the functionality of the Shell objects, users must enable the Initialize and script ActiveX Controls not marked as safe option for the security zone in which they are viewing the page.
Folder Objects
The Folder object represents a Shell folder. You can use the methods exposed by the Folder object to:
- Get information about a folder.
- Create subfolders.
- Copy and move file objects into the folder.
The FolderItem object represents an item in a Shell folder. Its properties enable you to retrieve information about the item. You can use the methods exposed by this object to run an item’s verbs, or to retrieve information about an item’s FolderItemVerbs object.
The FolderItems object represents a collection of items in a Shell folder. Its methods and properties enable you to retrieve information about the collection.
The following Visual Basic example shows the relationship between several of the folder objects and how they can be used together. When the user clicks the command button called cmdGetPath, the program displays a dialog box that enables the user to select a folder from My Computer, where ssfDRIVES is the ShellSpecialFolderConstants enumeration value for My Computer. When the user chooses a folder, the folder’s path is displayed in the text box called txtPath.
In VBScript, this function is slightly different because the ShellSpecialFolderConstants enumeration values are not available in script. The following example shows the VBScript equivalent of the previous example.
In the following JScript example, which is a direct translation of the preceding VBScript example, note how the empty parentheses ‘()’ are used to invoke the Items and Item methods.