Appendix S. The My Namespace

The My namespace provides shortcuts to make performing common tasks easier. The following sections describe the major items within the My namespace and describe the tools that they make available.

MY.APPLICATION

My.Application provides information about the current application. It includes properties that tell you the program's current directory, culture, Log object, and splash screen. It also includes information about the application's assembly, including the program's version numbering.

The following table describes the most useful My.Application properties, methods, and events.

ITEM

PURPOSE

ApplicationContext

Returns an ApplicationContext object for the currently executing thread. It provides a reference to the thread's form. Its ExitThread method terminates the thread and its ThreadExit event fires when the thread is exiting.

ChangeCurrentCulture

Changes the thread's culture used for string manipulation and formatting.

ChangeCurrentUICulture

Changes the thread's culture used for retrieving resources.

CommandLineArgs

Returns a collection containing the command-line argument strings used when the application was started. The first entry (with index 0) is the fully qualified name of the executable application.

CurrentCulture

Returns a CultureInfo object that represents the settings used for culture-specific string manipulation and formatting. This includes calendar information, date and time specifications, the culture's name, keyboard layout, number formats for general numbers (for example, the thousands separator character and decimal character), currency, and percentages.

CurrentUICulture

Returns a CultureInfo object that represents the culture-specific settings used by the thread to retrieve resources. It determines the culture used by the Resource Manager and My.Resources.

Deployment

Returns the application's current ApplicationDeployment object used for ClickOnce deployment. Normally, you don't need to manage deployment yourself, but this object lets you check for updates, start an update synchronously or asynchronously, download files, and restart the updated application.

DoEvents

Makes the application process all of the Windows messages currently waiting in the message queue. Doing this allows controls to process messages and update their appearances while the program is performing a long calculation. Often, you can avoid using DoEvents by performing long calculations on a separate thread, so the user interface can continue running normally.

GetEnvironment-Variable

Returns the value of the specified environment variable. For example, the following code displays the value of the PATH environment variable:

MessageBox.Show(
    My.Application.GetEnvironmentVariable("PATH"))

This method raises an exception if the named environment variable doesn't exist. The method Environment.GetEnvironmentVariable performs the same function, except that it returns Nothing if the variable doesn't exist.

Info

Returns an AssemblyInfo object that provides information about the assembly such as assembly name, company name, copyright, trademark, and version.

IsNetworkDeployed

Returns True if the application was deployed over the network. You should check this property and only try to use the My.Application.Deployment object if it returns True.

Log

An object of the class MyLog. You can use this object's WriteEntry and WriteException methods to log messages and exceptions.

MainForm

Gets or sets the application's main form.

NetworkAvailability-Changed

The application raises this event when the network's availability changes.

OpenForms

Returns a collection containing references to all of the application's open forms.

Shutdown

The application raises this event when it is shutting down. This event occurs after all forms' FormClosing and FormClosed event handlers have finished. Note that it only fires if the program shuts down normally. If it exits, these events don't fire.

SplashScreen

Gets or sets the application's splash screen.

Startup

The application raises this event when it is starting up before it creates any forms.

StartupNextInstance

The application raises this event when the user tries to start a second instance of a single-instance application.

UICulture

Gets the thread's culture used for retrieving resources.

UnhandledException

The application raises this event if it encounters an unhandled exception.

The following table lists the Info object's properties. Note that these properties have default blank values unless you set them by opening the project's property pages, selecting the Application tab, and clicking the Assembly Information button.

PROPERTY

PURPOSE

AssemblyName

Gets the assembly's name.

CompanyName

Gets the assembly's company name.

Copyright

Gets the assembly's copyright information.

Description

Gets the assembly's description.

DirectoryPath

Gets the directory where the assembly is stored.

LoadedAssemblies

Returns a collection of Assembly objects for the application's currently loaded assemblies.

ProductName

Gets the assembly's product name.

StackTrace

Gets a stack trace.

Title

Gets the assembly's title.

Trademark

Gets the assembly's trademark information.

Version

Gets the assembly's version number.

WorkingSet

Gets the number of bytes mapped to the process context.

The project's Application property page gives you access to most of the Info values at design time. To open the Application property page, open Solution Explorer, double-click the My Project entry, and select the Application tab.

To set Info values at design time, open the Application property page and click the Assembly Information button, and then enter the assembly information in the dialog shown in Figure S-1, and click OK.

Use this dialog box to enter information that the program can later retrieve using My.Application.AssemblyInfo.

Figure S.1. Use this dialog box to enter information that the program can later retrieve using My.Application.AssemblyInfo.

To place code in the My.Application object's NetworkAvailabilityChanged, Shutdown, Startup, StartupNextInstance, or UnhandledException event handlers, open the Application property page and click the View Application Events button.

Alternatively, you can open Solution Explorer, click the Show All Files button, expand the My Project entry, and open the file ApplicationEvents.vb.

To make the application a single-instance application, open the Application property page and check the "Make single instance application" box.

MY.COMPUTER

My.Computer provides methods to understand and control the computer's hardware and the system software. It lets you work with the audio system, clock, keyboard, clipboard, mouse, network, printers, Registry, and file system.

The following sections describe the properties, methods, and events available through My.Computer in detail.

Audio

This object provides access to the computer's audio system. Its methods let you play a .wav file synchronously or asynchronously, stop a file playing asynchronously, or play a system sound. For example, the following code plays the system's exclamation sound:

My.Computer.Audio.PlaySystemSound(SystemSounds.Exclamation)

The following table describes the Audio object's methods.

METHOD

PURPOSE

Play

Plays .wav data from a file, byte array, or stream. The second parameter can be Background (play asynchronously in the background), BackgroundLoop (play asynchronously in the background and repeat when it ends), or WaitToComplete (play synchronously).

PlaySystem-Sound

Plays a system sound. The parameter should be a member of the SystemSounds enumeration and can have the value Asterisk, Beep, Exclamation, Hand, or Question.

Stop

Stops the sound currently playing asynchronously.

Clipboard

The Clipboard object described in Chapter 23, "Drag and Drop, and the Clipboard," enables you to move data in and out of the system's clipboard. The My.Computer.Clipboard object provides extra tools that simplify some clipboard operations. The following table briefly summarizes the My.Computer.Clipboard object's methods.

METHOD

PURPOSE

Clear

Removes all data from the clipboard.

ContainsAudio

Returns True if the clipboard contains audio data.

ContainsData

Returns True if the clipboard contains data in a specific custom format.

ContainsFileDropList

Returns True if the clipboard contains a file drop list.

ContainsImage

Returns True if the clipboard contains image data.

ContainsText

Returns True if the clipboard contains textual data.

GetAudioStream

Gets audio data from the clipboard.

GetData

Gets data in a specific custom format from the clipboard.

GetDataObject

Gets a DataObject from the clipboard.

GetFileDropList

Gets a StringCollection holding the names of the files selected for drop from the clipboard.

GetImage

Gets image data from the clipboard.

GetText

Gets textual data from the clipboard.

SetAudio

Saves audio data to the clipboard.

SetData

Saves data in a specific custom format to the clipboard.

SetDataObject

Saves a DataObject to the clipboard.

SetFileDropList

Saves a StringCollection containing a series of fully qualified file names to the clipboard.

SetImage

Saves an image to the clipboard.

SetText

Saves textual data to the clipboard.

See Chapter 23 for more information about using the clipboard.

Clock

This property returns an object of type MyClock that you can use to learn about the current time. The following table describes this object's properties.

PROPERTY

PURPOSE

GmtTime

Returns a Date object that gives the current local date and time converted into Coordinated Universal Time (UTC) or Greenwich Mean Time (GMT).

LocalTime

Returns a Date object that gives the current local date and time.

TickCount

Returns the number of milliseconds since the computer started.

For example, suppose that you live in Colorado, which uses Mountain Standard Time (MST), seven hours behind Greenwich Mean Time. If My.Computer.Clock.LocalTime returns 2:03 PM, then My.Computer.Clock.GmtTime returns 9:03 PM.

If you must store a date and time for later use (for example, in a database), you should generally store it in UTC. Then you can meaningfully compare that value with other times stored on other computers in different time zones such as those across the Internet.

FileSystem

The FileSystem object provides tools for working with drives, directories, and files. The following table summarizes this object's properties and methods.

ITEM

DESCRIPTION

CombinePath

Returns a properly formatted combined path as a string.

CopyDirectory

Copies a directory.

CopyFile

Copies a file.

CreateDirectory

Creates a directory.

CurrentDirectory

Determines the fully qualified path to the application's current directory.

DeleteDirectory

Deletes a directory.

DeleteFile

Deletes a file.

DirectoryExists

Returns a Boolean indicating whether a directory exists.

Drives

Returns a read-only collection of DriveInfo objects describing the system's drives. See Chapter 38, "File-System Objects," for information about the DriveInfo class.

FileExists

Returns a Boolean indicating whether a file exists.

FindInFiles

Returns a collection holding names of files that contain a search string.

GetDirectories

Returns a String collection representing the path names of subdirectories within a directory.

GetDirectoryInfo

Returns a DirectoryInfo object for the specified path.

GetDriveInfo

Returns a DriveInfo object for the specified path.

GetFileInfo

Returns a FileInfo object for the specified path.

GetFiles

Returns a read-only String collection representing the names of files within a directory.

GetParentPath

Returns a string representing the absolute path of the parent of the provided path.

MoveDirectory

Moves a directory.

MoveFile

Moves a file.

OpenTextFieldParser

Opens a TextFieldParser.

OpenTextFileReader

Opens a TextReader.

OpenTextFileWriter

Opens a TextWriter.

ReadAllBytes

Reads from a binary file.

ReadAllText

Reads from a text file.

RenameDirectory

Renames a directory.

RenameFile

Renames a file.

SpecialDirectories

Returns a SpecialDirectoriesProxy object that has properties giving the locations of various special directories such as the system's temporary directory and the user's MyDocuments directory. See Chapter 38 for more information.

WriteAllBytes

Writes to a binary file.

WriteAllText

Writes to a text file.

Info

The My.Computer.Info object provides information about the computer's memory and operating system. The following list describes this object's properties:

PROPERTY

PURPOSE

AvailablePhysicalMemory

Returns the computer's total amount of free physical memory in bytes.

AvailableVirtualMemory

Returns the computer's total amount of free virtual address space in bytes.

InstalledUICulture

Returns the current user-interface culture.

LoadedAssemblies

Returns a collection of the assemblies loaded by the application.

OSFullName

Returns the computer's full operating-system name as in Microsoft Windows XP Home Edition.

OSPlatform

Returns the platform identifier for the operating system of the computer. This can be Unix, Win32NT (Windows NT or later), Win32S (runs on 16-bit Windows to provide access to 32-bit applications), Win32Windows (Windows 95 or later), or WinCE.

OSVersion

Returns the operating system's version in a string with the format major.minor.build.revision.

StackTrace

Returns a string containing the application's current stack trace.

TotalPhysicalMemory

Returns the computer's total amount of physical memory in bytes.

TotalVirtualMemory

Returns the computer's total amount of virtual address space in bytes.

WorkingSet

Returns the amount of physical memory mapped to the process context in bytes.

Keyboard

This object returns information about the current keyboard state. The following table describes this object's properties.

PROPERTY

PURPOSE

AltKeyDown

Returns True if the Alt key is down.

CapsLock

Returns True if Caps Lock is on.

CtrlKeyDown

Returns True if the Ctrl key is down.

NumLock

Returns True if Num Lock is on.

ScrollLock

Returns True if Scroll Lock is on.

ShiftKeyDown

Returns True if the Shift key is down.

The My.Computer.Keyboard object also provides one method named SendKeys. This method sends keystrokes to the currently active window just as if the user had typed them. You can use this method to provide some automated control over applications.

Mouse

The My.Computer.Mouse object provides information about the computer's mouse. The following table describes this object's properties.

PROPERTY

DESCRIPTION

ButtonsSwapped

Returns True if the functions of the mouse's left and right buttons have been switched. This can make using the mouse easier for left-handed users.

WheelExists

Returns True if the mouse has a scroll wheel.

WheelScrollLines

Returns a number indicating how much to scroll when the mouse wheel rotates one notch.

Name

The My.Computer.Name property simply returns the computer's name.

Network

The My.Computer.Network object provides a few simple properties and methods for working with the network. Its single property, IsAvailable, returns True if the network is available.

The following table describes the object's methods.

METHOD

DESCRIPTION

DownloadFile

Downloads a file from a remote computer. Parameters give such values as the file name, user name, password, and connection timeout.

IsAvailable

Returns True if the network is available.

Ping

Pings a remote computer to see if it is connected to the network.

UploadFile

Uploads a file to a remote computer. Parameters give such values as the file name, user name, password, and connection timeout.

This object also provides one event, NetworkAvailabilityChanged, that you can catch to learn when the network becomes available or unavailable.

Ports

This object provides one property and a single method. Its SerialPortNames property returns an array of strings listing the names of the computer's serial ports.

The OpenSerialPort method opens the serial port with a particular name (optional parameters give the baud rate, parity, and other port configuration information) and returns a reference to a SerialPort object.

The SerialPort class is much more complex than the My.Computer.Ports object. The following table describes the SerialPort class's most useful properties.

PROPERTY

PURPOSE

BaseStream

Returns the underlying Stream object.

BaudRate

Gets or sets the port's baud rate.

BreakState

Gets or sets the break signal state.

BytesToRead

Returns the number of bytes of data in the receive buffer.

BytesToWrite

Returns the number of bytes of data in the send buffer.

CDHolding

Returns the state of the port's Carrier Detect (CD) line.

CtsHolding

Returns the state of the port's Clear-to-Send (CTS) line.

DataBits

Gets or sets the standard length of data bits per byte.

DiscardNull

Determines whether null characters are ignored.

DsrHolding

Returns the state of the Data Set Ready (DSR) signal.

DtrEnable

Determines enabling of the Data Terminal Ready (DTR) signal.

Encoding

Determines the character encoding for text conversion.

Handshake

Determines the handshaking protocol.

IsOpen

Returns True if the port is open.

NewLine

Determines the end-of-line sequence for the ReadLine and WriteLine methods. This is a linefeed by default.

Parity

Determines the parity-checking protocol.

ParityReplace

Determines the character used to replace invalid characters when a parity error occurs.

PortName

Gets or selects the port.

ReadBufferSize

Determines the port's read buffer size.

ReadTimeout

Determines the read timeout in milliseconds.

ReceivedBytesThreshold

Determines the number of bytes in the input buffer before a ReceivedEvent is raised.

RtsEnable

Determines whether the Request to Transmit (RTS) signal is enabled.

StopBits

Determines the standard number of stop bits per byte.

WriteBufferSize

Determines the port's write buffer size.

WriteTimeout

Determines the write timeout in milliseconds.

The following table describes the SerialPort object's most useful methods.

METHOD

PURPOSE

Close

Closes the port.

DiscardInBuffer

Discards any data that is currently in the read buffer.

DiscardOutBuffer

Discards any data that is currently in the write buffer.

GetPortNames

Returns an array of strings holding the serial ports' names.

Open

Opens the port's connection.

Read

Reads data from the read buffer.

ReadByte

Synchronously reads one byte from the read buffer.

ReadChar

Synchronously reads one character from the read buffer.

ReadExisting

Reads all immediately available characters in both the stream and the read buffer.

ReadLine

Reads up to the next NewLine value in the read buffer.

ReadTo

Reads a string up to the specified value in the read buffer.

Write

Writes data into the port's write buffer.

WriteLine

Writes a string and a NewLine into the write buffer.

The SerialPort object also has a few events that you can use to learn about changes in the port's status. The following table describes the object's most useful events.

EVENT

PURPOSE

DataReceived

Occurs when the port receives data. The e.EventType parameter indicates the type of data and can be SerialData.Eof (end of file received) or SerialData.Chars (characters were received).

ErrorEvent

Occurs when the port encounters an error. The e.EventType parameter indicates the type of error and can be Frame (framing error), Overrun (character buffer overrun), RxOver (input buffer overrun), RxParity (hardware detected parity error), or TxFull (output buffer full).

PinChangedEvent

Occurs when the port's serial pin changes. The e.EventType parameter indicates the type of change and can be Break (break in the input), CDChanged (Receive Line Signal Detect, or RLSD, signal changed state), CtsChanged (CTS signal changed state), DsrChanged (DSR signal changed state), and Ring (detected a ring indicator).

Registry

My.Computer.Registry provides objects that manipulate the Registry. My.Computer.Registry has seven properties that refer to objects of type RegistryKey that represent the Registry's main subtrees or "hives."

The following table lists these objects and the corresponding Registry hives.

MY.COMPUTER.REGISTRY PROPERTY

REGISTRY SUBTREE

ClassesRoot

HKEY_CLASSES_ROOT

CurrentConfig

HKEY_CURRENT_CONFIG

CurrentUser

HKEY_CURRENT_USER

DynData

HKEY_DYNAMIC_DATA

LocalMachine

HKEY_LOCAL_MACHINE

PerformanceData

HKEY_PERFORMANCE_DATA

Users

HKEY_USERS

My.Computer.Registry also provides two methods, GetValue and SetValue, that get and set Registry values.

The program can use the RegistryKey objects to work with the corresponding Registry subtrees. The following table describes the most useful properties and methods provided by the RegistryKey class.

PROPERTY OR METHOD

PURPOSE

Close

Closes the key and writes it to disk if it has been modified.

CreateSubKey

Creates a new subkey or opens an existing subkey within this key.

DeleteSubKey

Deletes the specified subkey.

DeleteSubKeyTree

Recursively deletes a subkey and any child subkeys it contains.

DeleteValue

Deletes a value from the key.

Flush

Writes any changes to the key into the Registry.

GetSubKeyNames

Returns an array of strings giving subkey names.

GetValue

Returns the value of a specified value within this key.

GetValueKind

Returns the type of a specified value within this key. This can be Binary, DWord, ExpandString, MultiString, QWord, String, or Unknown. (Unknown is particularly important because the Registry can contain just about any custom data type.)

GetValueNames

Returns an array of strings giving the names of all of the values contained within the key.

Name

Returns the key's Registry path.

OpenSubKey

Returns a RegistryKey object representing a descendant key. A parameter indicates whether you need write access to the key.

SetValue

Sets a value within the key.

SubKeyCount

Returns the number of subkeys that are this key's direct children.

ToString

Returns the key's name.

ValueCount

Returns the number of values stored in this key.

Visual Basic's native Registry methods SaveSetting and GetSetting are generally easier to use than My.Computer.Registry, although they provide access to only part of the Registry.

Screen

The My.Computer.Screen property returns a Screen object representing the computer's main display. The following table describes the Screen object's most useful properties.

PROPERTY

PURPOSE

AllScreens

Returns an array of Screen objects representing all of the system's screens.

BitsPerPixel

Returns the screen's color depth in bits per pixel.

Bounds

Returns a Rectangle giving the screen's bounds in pixels.

DeviceName

Returns the screen's device name as in \.DISPLAY1.

Primary

Returns True if the screen is the computer's primary screen.

PrimaryScreen

Returns a reference to a Screen object representing the system's primary display. For a single display system, the primary display is the only display.

WorkingArea

Returns a Rectangle giving the screen's working area bounds in pixels. This is the desktop area excluding taskbars, docked windows, and docked toolbars.

The following table describes the Screen class's most useful methods.

METHOD

PURPOSE

FromControl

Returns a Screen object representing the display that contains the largest piece of a specific control.

FromHandle

Returns a Screen object representing the display that contains the largest piece of the object with a given handle.

FromPoint

Returns a Screen object representing the display that contains a given point.

FromRectangle

Returns a Screen object representing the display that contains the largest piece of a given Rectangle.

GetBounds

Returns a Rectangle giving the bounds of the screen that contains the largest piece of a control, rectangle, or point.

GetWorkingArea

Returns a Rectangle giving the working area of the screen that contains the largest piece of a control, rectangle, or point.

The AllScreens and PrimaryScreen properties, and all of these methods, are shared members of the Windows.Forms.Screen class. If you refer to them using an instance of the class such as My.Computer.Screen, the IDE flags the code with a warning. You can avoid the warning by using the class itself (System.Windows.Forms.Screen) rather than an instance to refer to these properties, as in the following code:

Debug.WriteLine(System.Windows.Forms.Screen.AllScreens(0).DeviceName)
Debug.WriteLine(System.Windows.Forms.Screen.PrimaryScreen.DeviceName)

The WorkingArea property does not update after you access the Screen object. If the user moves the system taskbar, the WorkingArea property does not show the new values.

The GetWorkingArea method retrieves the screen's current working area, however. If you must be certain that the user has not moved the taskbar or a docked object, use the GetWorkingArea method.

MY.FORMS

My.Forms provides properties that give references to an instance of each of the types of forms defined by the application. If the program begins with a startup form, the corresponding My.Forms entry refers to that form. For example, suppose the program begins by displaying Form1. Then, My.Forms.Form1 refers to the startup instance of the Form1 class.

You can also refer to these forms directly. For example, the following two statements set the text and display the predefined instance of the Form2 class:

My.Forms.Form2.Text = "Hello!"
Form2.Show()

Other forms that you create using the New keyword are separate instances from those provided by My.Forms.

If you know you will only want one instance of a particular form, for example if the form is a dialog box, you can use this instance instead of creating new instances of the class. If you will need to use more than one instance of the form at the same time, you must use New to create them.

You can set these properties to Nothing to dispose of the forms, but you can never set them to anything else. In particular, you cannot set them to new instances of their form classes later. When you destroy one of these instances, it is gone forever. If you will need to reuse the form later, set its Visible property to False rather than setting it equal to Nothing. Alternatively, you can just create new instances of the class when you need them and ignore the forms in My.Forms.

MY.RESOURCES

My.Resources provides access to the application's resources. Its ResourceManager property returns a reference to a ResourceManager object attached to the project's resources. You can use this object to retrieve the application's resources.

My.Resources also provides strongly typed properties that return the application's resources. For example, if you create a string resource named Greeting, the following code sets the form's caption to that string's value:

Me.Text = My.Resources.Greeting

See Chapter 36, "Configuration and Resources," for more information on using My.Resources to access the application's resources.

MY.USER

My.User returns information about the current user. The following table describes the My.User object's most useful properties.

PROPERTY OR METHOD

PURPOSE

CurrentPrincipal

Gets or sets an IPrincipal object used for role-based security.

InitializeWithWindowsUser

Sets the thread's principal to the Windows user who started it.

IsAuthenticated

Returns True if the user's identity has been authenticated.

IsInRole

Returns True if the user belongs to a certain role.

Name

Returns the current user's name in the format domainuser_name.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.138.138