Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Visual CSharp 2005 Recipes (2006) [eng]

.pdf
Скачиваний:
52
Добавлен:
16.08.2013
Размер:
4.04 Mб
Скачать

518 C H A P T E R 1 4 W I N D O W S I N T E G R AT I O N

14-8. Create a Shortcut on the Desktop or Start Menu

Problem

You need to create a shortcut on the user’s Windows desktop or Start menu.

Solution

Use COM Interop to access the functionality of the Windows Script Host. Create and configure an IWshShortcut instance that represents the shortcut. The folder in which you save the shortcut determines whether it appears on the desktop or in the Start menu.

How It Works

The .NET Framework class library does not include the functionality to create desktop or Start menu shortcuts; however, this is relatively easy to do using the Windows Script Host component accessed through COM Interop. Chapter 15 describes how to create an interop assembly that provides access to a COM component. If you are using Visual Studio, add a reference to the Windows Script Host Object Model listed in the COM tab of the Add Reference dialog box. If you don’t have Visual Studio .NET, use the Type Library Importer (Tlbimp.exe) to create an interop assembly for the wshom.ocx file, which is usually located in the Windows\System32 folder. (You can obtain the latest version of the Windows Script Host from http://msdn.microsoft.com/scripting. At the time of this writing, the latest version is 5.6.)

Once you have generated and imported the interop assembly into your project, follow these steps to create a desktop or Start menu shortcut.

1.Instantiate a WshShell object, which provides access to the Windows shell.

2.Use the SpecialFolders property of the WshShell object to determine the correct path of the folder where you want to put the shortcut. You must specify the name of the folder you want as an index to the SpecialFolders property. For example, to create a desktop shortcut, specify the value Desktop, and to create a start menu shortcut, specify StartMenu. Using the SpecialFolders property, you can obtain the path to any of the special system folders. If the specified folder does not exist on the platform you are running on, SpecialFolders returns an empty string. Other commonly used values include AllUsersDesktop and AllUsersStartMenu; you can find the full list of special folder names in the section on the SpecialFolders property in the Windows Script Host documentation.

3.Call the CreateShortcut method of the WshShell object, and provide the fully qualified filename of the shortcut file you want to create. The file should have the extension .lnk. CreateShortcut will return an IWshShortcut instance.

4.Use the properties of the IWshShortcut instance to configure the shortcut. You can configure properties such as the executable that the shortcut references, a description for the shortcut, a hotkey sequence, and the icon displayed for the shortcut.

5.Call the Save method of the IWshShortcut instance to write the shortcut to disk. The shortcut will appear either on the desktop or in the Start menu (or elsewhere) depending on the path specified when the IWshShortcut instance was created.

C H A P T E R 1 4 W I N D O W S I N T E G R AT I O N

519

The Code

The following example class creates a shortcut to Notepad.exe on both the desktop and Start menu of the current user. The example creates both shortcuts by calling the CreateShortcut method and specifying a different destination folder for each shortcut file. This approach makes it possible to create the shortcut file in any of the special folders returned by the WshShell.SpecialFolders property.

using System; using System.IO;

using IWshRuntimeLibrary;

namespace Apress.VisualCSharpRecipes.Chapter14

{

class Recipe14_08

{

public static void CreateShortcut(string destination)

{

//Create a WshShell instance through which to access the

//functionality of the Windows shell.

WshShell wshShell = new WshShell();

//Assemble a fully qualified name that places the Notepad.lnk

//file in the specified destination folder. You could use the

//System.Environment.GetFolderPath method to obtain a path, but

//the WshShell.SpecialFolders method provides access to a wider

//range of folders. You need to create a temporary object reference

//to the destination string to satisfy the requirements of the

//Item method signature.

object destFolder = (object)destination; string fileName = Path.Combine(

(string)wshShell.SpecialFolders.Item(ref destFolder), "Notepad.lnk"

);

//Create the shortcut object. Nothing is created in the

//destination folder until the shortcut is saved. IWshShortcut shortcut =

(IWshShortcut)wshShell.CreateShortcut(fileName);

//Configure the fully qualified name to the executable.

//Use the Environment class for simplicity. shortcut.TargetPath = Path.Combine(

Environment.GetFolderPath(Environment.SpecialFolder.System),

"notepad.exe"

);

//Set the working directory to the Personal (My Documents) folder. shortcut.WorkingDirectory =

Environment.GetFolderPath(Environment.SpecialFolder.Personal);

//Provide a description for the shortcut.

shortcut.Description = "Notepad Text Editor";

// Assign a hotkey to the shortcut. shortcut.Hotkey = "CTRL+ALT+N";

520C H A P T E R 1 4 W I N D O W S I N T E G R AT I O N

//Configure Notepad to always start maximized. shortcut.WindowStyle = 3;

//Configure the shortcut to display the first icon in Notepad.exe. shortcut.IconLocation = "notepad.exe, 0";

//Save the configured shortcut file.

shortcut.Save();

}

public static void Main()

{

//Create the Notepad shortcut on the desktop. CreateShortcut("Desktop");

//Create the Notepad shortcut on the Windows Start menu of

//the current user.

CreateShortcut("StartMenu");

// Wait to continue. Console.WriteLine(Environment.NewLine); Console.WriteLine("Main method complete. Press Enter."); Console.ReadLine();

}

}

}

A P P E N D I X

■ ■ ■

Acronyms

ACL

access control list

API

Application Programming Interface

ASCII

American Standard Code for Information Interchange

CA

certificate authority

CAS

code access security

CCW

COM callable wrapper

CLR

common language runtime

COM

Component Object Model

CPU

central processing unit

CSP

cryptographic service provider

CSS

Cascading Style Sheets

521

522 A P P E N D I X A C R O N Y M S

DB

database

DCOM

Distributed Component Object Model

DLL

dynamic link library

DNS

Domain Name System

DOM

Document Object Model

DPAPI

Data Protection Application Programming Interface

FTP

File Transfer Protocol

GAC

global assembly cache

GC

garbage collector

GDI

Graphical Device Interface

GUI

graphical user interface

HTML

Hypertext Markup Language

HTTP

Hypertext Transfer Protocol

HTTPS

Hypertext Transfer Protocol over Secure Sockets Layer (HTTP over SSL)

I/O

input/output

A P P E N D I X A C R O N Y M S

523

ICMP

Internet Control Message Protocol

IIS

Internet Information Services

IL

intermediate language

IMAP

Internet Message Access Protocol

IP

Internet Protocol

JIT

just in time

MAPI

Messaging Application Programming Interface

MBR

marshal by reference

MBV

marshal by value

MDI

Multiple Document Interface

MIME

Multipurpose Internet Mail Extensions

MSDE

Microsoft SQL Server Desktop Engine

MSDN

Microsoft Developer Network

MSIL

Microsoft Intermediate Language

OS

operating system

524 A P P E N D I X A C R O N Y M S

PIA

primary interop assembly

PID

process identifier

POP3

Post Office Protocol 3

RBS

role-based security

RCW

runtime callable wrapper

RFC

Request For Comment

RID

role identifier

RPC

remote procedure call

SCM

Service Control Manager

SDK

software development kit

SID

security identifier

SMTP

Simple Mail Transfer Protocol

SOAP

Simple Object Access Protocol

SPC

software publisher certificate

SQL

Structured Query Language

A P P E N D I X A C R O N Y M S

525

SSL

Secure Sockets Layer

TCP

Transmission Control Protocol

UDP

User Datagram Protocol

URI

uniform resource identifier

URL

uniform resource locator

URN

uniform resource name

UTF

Unicode Transformation Format

W3C

World Wide Web Consortium

WMI

Windows Management Instrumentation

WSDL

Web Service Description Language

XML

Extensible Markup Language

XSD

XML Schema Definition

XSL

Extensible Style Language

XSLT

Extensible Style Language Transformation

Index

Symbols

#define directive, 13 #elif directive, 12 #else directive, 12 #endif directive, 12

logical operators supported by, 12 #if directive, 12

logical operators supported by, 12 #undef directive, 13

&& logical AND operator, 13 || OR operator, 13

(!=) inequality operator, 13

supported by TimeSpan and DateTime structures, 49

(<) less than operator

supported by TimeSpan and DateTime structures, 50

(<=) less than or equal to operator supported by TimeSpan and DateTime

structures, 50

(>) greater than operator

supported by TimeSpan and DateTime structures, 50

(>=) greater than or equal to operator supported by TimeSpan and DateTime

structures, 50 () operator, 13

(+) addition operator

supported by TimeSpan and DateTime structures, 49

(+) unary plus operator

supported by TimeSpan and DateTime structures, 50

(-) subtraction operator

supported by TimeSpan and DateTime structures, 49

(-) unary negation operator

supported by TimeSpan and DateTime structures, 50

(=) assignment operator

supported by TimeSpan and DateTime structures, 49

(==) equality operator

supported by TimeSpan and DateTime structures, 49

* (asterisk)

as placeholder for element names, 192 -Vr switch

Strong Name tool, 20 -Vu switch

Strong Name tool, 21

.NET. See NET

/addmodule compiler switch, 7 /define compiler switch, 13 /delaysign switch, 20 /keycontainer compiler switch, 18 /keyfile compiler switch, 18 /main switch, 2

/out switch, 2

/reference compiler switch, 10 /target

exe switch, 2

module compiler switch, 7 == equality operator, 13

A

Abort method HttpListenerContext class, 347 Thread class, 83, 132

AcceptTcpClient method TcpListener class, 360, 363–364

access control lists manipulating, 180–182

access tokens, 418 accessing

ADO objects using COM interop, 451 command-line arguments, 10–11 elements with same name as keywords, 15

AccountOperator value WindowsBuiltInRole enumeration, 413

Activator class CreateInstance method, 90

CreateInstanceFrom method, 90 System namespace, 90

ActiveMovie COM component, 277, 279 ActiveX controls

using in .NET clients, 454–455 Add method

ControlCollection class, 214 CredentialCache class, 376 HttpListenerPrefixCollection collection, 346 Interlocked class, 129

Parameters collection, 315–316, 328 AddClosedCurve method

GraphicsPath class, 263 AddEllipse method

GraphicsPath class, 263 addition (+) operator

supported by TimeSpan and DateTime structures, 49

AddPrinterConnection method Win32_Printer class, 298

527

Соседние файлы в предмете Программирование на C++