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 |
---|---|
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). |
PlaySystemSound | 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. |
The Clipboard object described in Chapter 13 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 13 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 |
---|---|
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 P.M., then My.Computer.Clock.GmtTime returns 9:03 P.M.
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 |
---|---|
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 29 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 29 for more information. |
WriteAllBytes | Writes to a binary file. |
WriteAllText | 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 |
---|---|
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. |
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.
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. |
The My.Computer.Name property simply returns the computer’s name.
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, username, 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, data bits, and stop bits) 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). |
My.Computer.Registry provides objects that manipulate the Registry. My.Computer.Registry has seven properties that refer to objects of type RegistryKey. The following table lists these objects and the corresponding Registry subtrees.
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. |
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 don’t provide access to the entire 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 |
---|---|
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.