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 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 |
---|---|
| 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. |
| Changes the thread's culture used for string manipulation and formatting. |
| Changes the thread's culture used for retrieving resources. |
| 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. |
| 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. |
| 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. |
| 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. |
| 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. |
| 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. |
| Returns an AssemblyInfo object that provides information about the assembly such as assembly name, company name, copyright, trademark, and version. |
| 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. |
| An object of the class MyLog. You can use this object's WriteEntry and WriteException methods to log messages and exceptions. |
| Gets or sets the application's main form. |
| The application raises this event when the network's availability changes. |
| Returns a collection containing references to all of the application's open forms. |
| 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. |
| Gets or sets the application's splash screen. |
| The application raises this event when it is starting up before it creates any forms. |
| The application raises this event when the user tries to start a second instance of a single-instance application. |
| Gets the thread's culture used for retrieving resources. |
| 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 |
---|---|
| Gets the assembly's name. |
| Gets the assembly's company name. |
| Gets the assembly's copyright information. |
| Gets the assembly's description. |
| Gets the directory where the assembly is stored. |
| Returns a collection of Assembly objects for the application's currently loaded assemblies. |
| Gets the assembly's product name. |
| Gets a stack trace. |
| Gets the assembly's title. |
| Gets the assembly's trademark information. |
| Gets the assembly's version number. |
| 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.
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 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.
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 |
---|---|
| 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). |
| 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. |
| Stops the sound currently playing asynchronously. |
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 |
---|---|
| Removes all data from the clipboard. |
| Returns True if the clipboard contains audio data. |
| Returns True if the clipboard contains data in a specific custom format. |
| Returns True if the clipboard contains a file drop list. |
| Returns True if the clipboard contains image data. |
| Returns True if the clipboard contains textual data. |
| Gets audio data from the clipboard. |
| Gets data in a specific custom format from the clipboard. |
| Gets a DataObject from the clipboard. |
| Gets a StringCollection holding the names of the files selected for drop from the clipboard. |
| Gets image data from the clipboard. |
| Gets textual data from the clipboard. |
| Saves audio data to the clipboard. |
| Saves data in a specific custom format to the clipboard. |
Saves a DataObject to the clipboard. | |
| Saves a StringCollection containing a series of fully qualified file names to the clipboard. |
| Saves an image to the clipboard. |
| Saves textual data to the clipboard. |
See Chapter 23 for more information about using the clipboard.
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 |
---|---|
| Returns a Date object that gives the current local date and time converted into Coordinated Universal Time (UTC) or Greenwich Mean Time (GMT). |
| Returns a Date object that gives the current local date and time. |
| 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.
The FileSystem object provides tools for working with drives, directories, and files. The following table summarizes this object's properties and methods.
ITEM | DESCRIPTION |
---|---|
| Returns a properly formatted combined path as a string. |
| Copies a directory. |
| Copies a file. |
| Creates a directory. |
| Determines the fully qualified path to the application's current directory. |
| Deletes a directory. |
| Deletes a file. |
| Returns a Boolean indicating whether a directory exists. |
| 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. |
| Returns a Boolean indicating whether a file exists. |
| Returns a collection holding names of files that contain a search string. |
| Returns a String collection representing the path names of subdirectories within a directory. |
| Returns a DirectoryInfo object for the specified path. |
| Returns a DriveInfo object for the specified path. |
| Returns a FileInfo object for the specified path. |
| Returns a read-only String collection representing the names of files within a directory. |
| Returns a string representing the absolute path of the parent of the provided path. |
| Moves a directory. |
| Moves a file. |
| Opens a TextFieldParser. |
| Opens a TextReader. |
| Opens a TextWriter. |
| Reads from a binary file. |
| Reads from a text file. |
| Renames a directory. |
| Renames a file. |
| 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. |
| Writes to a binary file. |
| Writes to a text file. |
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 |
---|---|
| Returns the computer's total amount of free physical memory in bytes. |
| Returns the computer's total amount of free virtual address space in bytes. |
| Returns the current user-interface culture. |
| Returns a collection of the assemblies loaded by the application. |
| Returns the computer's full operating-system name as in Microsoft Windows XP Home Edition. |
| 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. |
| Returns the operating system's version in a string with the format major.minor.build.revision. |
| Returns a string containing the application's current stack trace. |
| Returns the computer's total amount of physical memory in bytes. |
| Returns the computer's total amount of virtual address space in bytes. |
| Returns the amount of physical memory mapped to the process context in bytes. |
This object returns information about the current keyboard state. The following table describes this object's properties.
PROPERTY | PURPOSE |
---|---|
| Returns True if the Alt key is down. |
| Returns True if Caps Lock is on. |
| Returns True if the Ctrl key is down. |
| Returns True if Num Lock is on. |
| Returns True if Scroll Lock is on. |
| 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.
The My.Computer.Mouse object provides information about the computer's mouse. The following table describes this object's properties.
PROPERTY | DESCRIPTION |
---|---|
| 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. |
| Returns True if the mouse has a scroll wheel. |
| Returns a number indicating how much to scroll when the mouse wheel rotates one notch. |
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 |
---|---|
| Downloads a file from a remote computer. Parameters give such values as the file name, user name, password, and connection timeout. |
| Returns True if the network is available. |
| Pings a remote computer to see if it is connected to the network. |
| 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.
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 |
---|---|
| Returns the underlying Stream object. |
| Gets or sets the port's baud rate. |
| Gets or sets the break signal state. |
| Returns the number of bytes of data in the receive buffer. |
| Returns the number of bytes of data in the send buffer. |
| Returns the state of the port's Carrier Detect (CD) line. |
| Returns the state of the port's Clear-to-Send (CTS) line. |
| Gets or sets the standard length of data bits per byte. |
| Determines whether null characters are ignored. |
| Returns the state of the Data Set Ready (DSR) signal. |
Determines enabling of the Data Terminal Ready (DTR) signal. | |
| Determines the character encoding for text conversion. |
| Determines the handshaking protocol. |
| Returns True if the port is open. |
| Determines the end-of-line sequence for the ReadLine and WriteLine methods. This is a linefeed by default. |
| Determines the parity-checking protocol. |
| Determines the character used to replace invalid characters when a parity error occurs. |
| Gets or selects the port. |
| Determines the port's read buffer size. |
| Determines the read timeout in milliseconds. |
| Determines the number of bytes in the input buffer before a ReceivedEvent is raised. |
| Determines whether the Request to Transmit (RTS) signal is enabled. |
| Determines the standard number of stop bits per byte. |
| Determines the port's write buffer size. |
| Determines the write timeout in milliseconds. |
The following table describes the SerialPort object's most useful methods.
METHOD | PURPOSE |
---|---|
| Closes the port. |
| Discards any data that is currently in the read buffer. |
| Discards any data that is currently in the write buffer. |
| Returns an array of strings holding the serial ports' names. |
| Opens the port's connection. |
| Reads data from the read buffer. |
| Synchronously reads one byte from the read buffer. |
Synchronously reads one character from the read buffer. | |
| Reads all immediately available characters in both the stream and the read buffer. |
| Reads up to the next NewLine value in the read buffer. |
| Reads a string up to the specified value in the read buffer. |
| Writes data into the port's write buffer. |
| 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 |
---|---|
| 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). |
| 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). |
| 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). |
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.
REGISTRY SUBTREE | |
---|---|
| HKEY_CLASSES_ROOT |
| HKEY_CURRENT_CONFIG |
| HKEY_CURRENT_USER |
| HKEY_DYNAMIC_DATA |
| HKEY_LOCAL_MACHINE |
| HKEY_PERFORMANCE_DATA |
| 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 |
---|---|
| Closes the key and writes it to disk if it has been modified. |
| Creates a new subkey or opens an existing subkey within this key. |
| Deletes the specified subkey. |
| Recursively deletes a subkey and any child subkeys it contains. |
| Deletes a value from the key. |
| Writes any changes to the key into the Registry. |
| Returns an array of strings giving subkey names. |
| Returns the value of a specified value within this key. |
| 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.) |
| Returns an array of strings giving the names of all of the values contained within the key. |
| Returns the key's Registry path. |
| Returns a RegistryKey object representing a descendant key. A parameter indicates whether you need write access to the key. |
| Sets a value within the key. |
| Returns the number of subkeys that are this key's direct children. |
| Returns the key's name. |
| 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.
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 |
---|---|
| Returns an array of Screen objects representing all of the system's screens. |
| Returns the screen's color depth in bits per pixel. |
| Returns a Rectangle giving the screen's bounds in pixels. |
| Returns the screen's device name as in \.DISPLAY1. |
| Returns True if the screen is the computer's primary screen. |
| 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. |
| 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 |
---|---|
| Returns a Screen object representing the display that contains the largest piece of a specific control. |
| Returns a Screen object representing the display that contains the largest piece of the object with a given handle. |
Returns a Screen object representing the display that contains a given point. | |
| Returns a Screen object representing the display that contains the largest piece of a given Rectangle. |
| Returns a Rectangle giving the bounds of the screen that contains the largest piece of a control, rectangle, or point. |
| 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 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 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 returns information about the current user. The following table describes the My.User object's most useful properties.
PROPERTY OR METHOD | PURPOSE |
---|---|
| Gets or sets an IPrincipal object used for role-based security. |
| Sets the thread's principal to the Windows user who started it. |
| Returns True if the user's identity has been authenticated. |
| Returns True if the user belongs to a certain role. |
| Returns the current user's name in the format domainuser_name. |