Abs Function VB.NET

Class
System.Math

Syntax

Return Value
The absolute value ofvalue. The data type is the same as that of the argument passed to the function.

Description
Returns the absolute value ofvalue.Ifvalueis an uninitialized variable, the return value is 0.

Rules at a Glance

Only numeric values can be passed to theAbsfunction.

This is a Shared member of the Math class, so it can be used without creating any objects.

Example
In this example, theLineLengthfunction is used to determine the length of a line on the screen. If the line runs from left to right,X1is less thanX2, and the expression X2 - X1 returns the length of the line. If, however, the line runs from right to left,X1is greater thanX2, and a negative line length is returned. As you know, in most circumstances it does not matter which way a line is pointing; all you want to know is how long it is. Using theAbsfunction allows you to return the same figure whether the underlying figure is negative or positive:

Programming Tips and Gotchas
Because theAbsfunction can only accept numeric values, you may want to check the value you pass toAbsusing theIs Numericfunction to avoid generating an error. This is illustrated in the following code snippet:

VB .NET/VB 6 Differences
In VB 6,Absis an intrinsic VB function. In the .NET platform, it is a member of the Math class in the System namespace, and so it is not part of the VB .NET language.

Acos Function
Class
System.Math

Syntax

A cosine, which is a number greater than or equal to -1 and less than or equal to 1

Return Value
A Double between 0 and pi that is the arccosine ofdin radians

Description
Returns the arccosine ofdin radians

Rules at a Glance

Ifdis out of range (less than -1 or greater than 1),Acosreturns NaN.

This is a Shared member, so it can be used without creating any objects.

Programming Tips and Gotchas
To convert from radians to degrees, multiply by 180/pi.

VB .NET/VB 6 Differences
TheAcosfunction did not exist in VB 6.

AddHandler Statement
Syntax
AddHandlerNameOfEventSender, AddressOfNameOfEventHandler

NameOfEventSender

NameOfEventHandler

The name of a subroutine that is to serve as the event handler forNameOfEventSender

Description
Binds an event handler to a built-in or custom event. This makes it possible to bind several event handlers to a single event.

EventNameOfSendertakes the formclass.eventorobject.event.

You can stop handling events defined by the AddHandler statement by calling the RemoveHandler statement.

Programming Tips and Gotchas
The WithEvents keyword can be used to receive event notification for the lifetime of an object. In contrast, AddHandler and RemoveHandler can be used to dynamically add and remove event notification at runtime.

AddressOf Operator
Syntax
AddressOfprocedurename
Procedurename

Description
The AddressOf operator returns a procedure delegate instance that references a specific procedure. The AddressOf operator is used in the following situations:

If a parameter to a procedure (a VB procedure or a Win32 API function) requires a function pointer (the address of a function), then we can pass the expression:

AddressOffunctionname

wherefunctionnameis the name of the function. This function is called acallback function.

AddressOf is also used to create delegate objects, as in:

delg = New ADelegate(AddressOf obj.AMethod)

AddressOf is used to bind event handlers to events through the AddHandler statement:

AddHandler Form1.Click, AddressOf Me.Form1Click

VB .NET/VB 6 Differences

In VB 6, the AddressOf operator can only be used in a call to a Windows API function. Moreover, the argument passed to AddressOf must be the name of a procedure in a standard code module. However, in VB .NET these restrictions no longer apply.

AppActivate Procedure

Class

Microsoft.VisualBasic.Interaction

Syntax
[Interaction.]AppActivate(title)
title

The name of the application as currently shown in the application window title bar. This can also be the task ID returned from theShellfunction.

Description
Activates a window based on its caption

Rules at a Glance

AppActivate performs a case-insensitive search on all top-level windows for a window caption that matchestitle. If an exact match is found, the window is activated. If no match is found, then the window captions are searched for a prefix match (titlematches the beginning of the window caption). For example, thetitle"Microsoft Word" matches "Microsoft Word - MyDocument.doc". If a prefix match is found, the window is activated. Note that if multiple prefix matches are found, there is no way to predict which matching window will be activated.

The window state (Maximized, Minimized, or Normal) of the activated application is not affected by AppActivate.

If a matching application cannot be found, an exception of type System.ArgumentException is raised, and runtime error 5, "Invalid procedure call or argument," is generated.

Example

Programming Tips and Gotchas

AppActivate searches only top-level windows.

You can also use the task ID returned by theShellfunction with the AppActivate statement,as this simple example demonstrates:

AppActivate is very difficult to use with applications whose application titles change to reflect the state or context of the application. Microsoft Outlook illustrates an excellent example of this problem. If the user has Outlook in the Calendar section, the title bar reads "Calendar - Microsoft Outlook," whereas if in the Inbox section, the title bar reads "Inbox - Microsoft Outlook." In situations such as this, we must resort to other techniques, such as using Win32 API methods, to enumerate all windows and check the captions directly.

AppActivate is often used to give the focus to a particular window before keystrokes are sent to it using the SendKeys statement, which sends keystrokes to the active window only.

VB .NET/VB 6 Differences
In VB 6, AppActivate has a second optional parameter,wait, a Boolean that determines whether the application calling AppActivate must have the focus for the window indicated bytitleto be activated. In VB .NET,waitis not supported.

Application Class

Namespace
System.Windows.Forms

Createable
No

Description
The Application object provides a diverse range of functionality, including support for multithreaded programming, access to the system registry, and support for subclassing (intercepting messages sent to application windows). It also includes a variety of informational functions, such as properties to retrieve the company name, to retrieve the application's executable path, and to retrieve the application's name and version.
Application objects can be created as follows:
Dim obj As Application

However, because all of the Application object's members are shared, you do not need to instantiate the Application object to access its properties and methods. Hence, you can retrieve the executable path of your application, for instance, with the code fragment:
Dim sPath As String = Application.ExecutablePath
Application class members marked with a plus sign (+) are discussed in detail in their own entries.

Application.CompanyName Property
Class
System.Windows.Forms.Application

Syntax
Application.CompanyName( )

Return Value
A String containing the company name for the application

Description
Gets the company name for the application. This is a read-only property.

The value of the CompanyName property can be defined by including the <AssemblyCompany>attribute in the AssemblyInfo file for the application. Its syntax is:

wheresCompanyis a string literal containing the company name.

Application.DoEvents Method

Class
System.Windows.Forms.Application

Syntax
Application.DoEvents( )

Description
Allows the operating system to process events and messages waiting in the message queue.

For example, you can allow a user to click a Cancel button while a processor-intensive operation is executing. In this case, without DoEvents, the click event is not processed until after the operation had completed. With DoEvents, Windows allocates time for the Cancel button's Click event to fire and the event handler to execute.

Example
The following example uses a form with two command buttons to illustrate DoEvents. Suppose the user clicks CommandButton1. Then the Do loop in the click event executes indefinitely. However, if the user clicks CommandButton2, its click event is processed when the DoEvents statement in CommandButton1_Click is executed. This sets the Boolean flag to False, which terminates the Do loop.Option Explicit

Programming Tips and Gotchas

While DoEvents can be indispensable for increasing the responsiveness of your application, it should at the same time be used judiciously, since it entails an enormous performance penalty. For example, the following table compares the number of seconds required for a simple For Next loop to iterate one million times when DoEvents isn't called,on the one hand,and when it's called on each iterationof the loop,on the other.

Programming Tips and Gotchas

If most of a procedure's processing occurs inside of a loop, one way to avoid too many calls to DoEvents is to call it conditionally every ten, hundred, or thousand iterations of the loop. For example, the following code calls DoEvents every thousand iterations:

DoEvents should not be used in any event procedure or callback routine that is invoked automatically by the operating system. Doing so causes re-entrance problems. (The event or routine may be called again during the processing of the DoEvents method.) For the same reason, DoEvents should not be used in in-process COM objects created with Visual Basic.

Application.ExecutablePath Property

Class
System.Windows.Forms.Application

Syntax
Application.ExecutablePath( )

Return Value
A String containing the complete path of the executable file for the application

Description
Gets the complete path of the executable file for the application. This is a read-only property.

VB .NET/VB 6 Differences
The ExecutablePath property in the .NET Framework corresponds to the App.Path property in VB 6.

Application.ProductName Property
Class
System.Windows.Forms.Application

Syntax
Application.ProductName( )

Return Value
A String containing the product name of the application

Description
Gets the product name of the application. This is a read-only property.

The value of the ProductName property can be defined by including the <AssemblyProduct>attribute in the application's AssemblyInfo file. Its syntax is:

whereProductis a string literal containing the product name.

VB .NET/VB 6 Differences
The ProductName property in the .NET Framework corresponds to the App.ProductName property in VB 6.

Application.ProductVersion Property

Class
System.Windows.Forms.Application
Syntax
Application.ProductVersion( )

Return Value
A String containing the product version of the application

Description
Gets the product version of the application. This is a read-only property. The product version typically has the form:
MajorVersionNumber.MinorVersionNumber.BuildNumber.PrivatePartNumberIts default value is "1.0.*", which indicates that Visual Studio maintains default build and revision numbers.The value of the ProductVersion property can be defined by including the <AssemblyVersion>attribute in the application's AssemblyInfo file. Its syntax is:

wheremajis the major version number,minis the minor version number,bldis the build number, andrevis the revision number.

VB .NET/VB 6 Differences
The ProductVersion property in the .NET Framework corresponds to the App.Major, App.Minor, and
App.Revision properties in VB 6.

Array Class
Namespace
System

Createable
Yes

Description
An Array object (that is, an instance of the Array class) that represents an array.

Arrays defined in VB .NET are Array objects, so they support the members of the Array class. Arrayclass members marked with a plus sign (+) are discussed in detail in their own entries.

Array.BinarySearch Method
Class
System.Array

Syntax
Array.BinarySearch(array,value, [comparer])
Array.BinarySearch(array, index, length, value, [comparer])

Return Value
An Integer representing the zero-based ordinal position of the element matchingvalue

Description

This method provides a quick way to search for a value in asortedone-dimensional array, returning the smallest index whose element is that value. It uses a binary search algorithm, which tends to take log2(n) comparisons to find an item in an array of length n. For example, if n = 100,000, the number of comparisons is on the order of 17.

To illustrate, if arr is an array of names in alphabetical order, then the code:

returns the smallest index with element "steve." If no such element exists, BinarySearch returns the negative number whose bitwise complement is the index of the first element that is larger than "steve."

Rules at a Glance

The array must be a one-dimensional array sorted inascendingorder.

Ifvalueis not found in the array, the method returns a negative number, which is the bitwise complement of the index of the first element that is larger thanvalue. To extract this value, you can use the Not operator, as in the following code fragment:

By default, the System.Collections.Comparer class is used to comparevaluewith the members ofarray. This means that string comparisons are case sensitive.

Programming Tips and Gotchas

If an array contains Boolean values, the method fails to correctly identify the position of the first False value in the array.

In addition to the Comparer class, you can also pass an instance of the system.Collections.CaseInsensitiveComparer class as thecomparerargument. It provides for case-insensitive comparisons. For example:

In this case, because of the case-insensitive comparison, the value of Result is 2.

Array.Copy Method

Return Value
None

Description
Makes a copy of all or part of an array.
Since arrays are reference types, when we set one array variable equal to another, we are justassigning a new reference to the same array. For instance, consider the following code:

The fact that changing b(0) also changes a(0) shows that a and b point to the same array.

Rules at a Glance

Using the first syntax, you can copy a range of values from the beginning ofsourceArrayto the beginning ofdestinationArray. Using the second syntax, you can copy a range of values from anywhere indestinationArrayto anywhere intargetArray.

sourceArrayanddestinationArraymust have the same number of dimensions.

lengthis the total number of elements to be copied. If sArr1 is a two-dimensional array, forexample, the statement:

copies the values from sArr(0,0), sArr(0,1), and sArr(1,0) to sArr2.

To copy all elements, you can supply UBound(sourceArray) + 1 as an argument tolength.

IfsourceArrayanddestinationArrayare the same, anddestinationIndexlies within the range of values being copied (that is, if the source and target ranges overlap), no data will be lost. The method behaves as if it copieslengthelements fromsourceArrayto a temporary buffer, then copies from the temporary buffer todestinationArray.

Example

VB .NET/VB 6 Differences
Since arrays were not a reference type in VB 6, you could simply create a copy of an existing array
through assignment, thus eliminating the need for a Copy method.

Array.IndexOf Method

Return Value
The index of the first occurrence ofValueinArray, or -1

Description
Returns an Integer representing the index of the first occurrence ofobjectinArray

Rules at a Glance

Arraymust be a one-dimensional array.

By default, the IndexOf method searches forValuefrom the beginning to the end ofArray.

IfstartIndexis provided withoutcount, IndexOf searches fromstartIndex;to the last element ofArray.

If bothstartIndexandcountare provided, the method searchescountelements starting atstartIndex. In other words, it searches from array(startIndex) to array(startIndex + count - 1).

IfstartIndexis present and is outside of the range of the elements in array, the method returns -1.

Ifcountis present and startIndex + count - 1 exceeds the total number of elements inarray, the method call generates an ArgumentOutOfRangeException exception.

Example

The following code searches for a value in an Integer array:

You can also specify the starting index for the search, as well as the number of elements to search. For example:

Array.IndexOf(array:=a, value:=136500, startIndex:=100, _count:=1000)

Array.LastIndexOf Method

Return Value
An Integer containing the index of the last occurrence ofObjectinArray

Description
Returns the index of the last occurrence ofObjectinArray

Rules at a Glance

Array;must be a one-dimensional array.

The LastIndexOf method has the same syntax as the IndexOf method and works the same way as IndexOf, except that it searches from the end of the array and returns the largest index of a matching element.

By default, the LastIndexOf method searches forValuefrom the end to the beginning ofArray.

IfstartIndexis provided withoutcount, LastIndexOf searches fromstartIndexto the first element ofArray.

If bothstartIndexandcountare provided, the method searchescountelements backward starting atstartIndex. In other words, it searches from array(startIndex) to array(startIndex - count + 1).

IfstartIndexis present and is outside of the range of the elements inarray, the method returns -1.

Ifcountis present and startIndex < count - 1, the method call generates an ArgumentOutOfRangeException exception.

Example
The following code searches for a value in an Integer array:

You can also specify the starting index for the search, as well as the number of elements to search. For example:

Array.Reverse Method

Return Value

None

Description
Reverses a portion of or all of the elements of an array.

Example

This code prints the sequence 14325, which is the original array 12345 with the middle section from index 1 to index 3 reversed.

Array.Sort Method

A parallel array of values to be sorted in the order ofkeys, their corresponding keys

An object implementing the IComparer interface to be used for sorting. If Nothing, then the IComparable implementation of each element (in the case of arrays of keys) or value type (in the case of arrays).

Return Value

None

Description
Sorts a portion of, or sorts an entire one-dimensional array, with an optionally specified key array and
an optionally specified IComparer interface

Example

The output is:
9
8
12
4
5
Sorted:
4
5
8
9
12

Asc, AscW Functions

Return Value
An Integer that represents the character code of the first character of the string. The range for the
returned value is 0 - 255 on nonDBCS systems, but -32768 to 32767 on DBCS systems.

Description
Returns an Integer representing the character code for the first character of the string passed to it. All
other characters in the string are ignored

Rules at a Glance

The string expression passed to the function must contain at least one character or a runtime error is generated.

Only the first character of the string is evaluated byAscorAscW.

Example

Programming Tips and Gotchas

Check that the string you are passing to the function contains at least one character using theLenfunction, as the following example shows:

UseAscwithin your data-validation routines to determine such conditions as whether the firstcharacter is upper- or lowercase and whether it is alphabetic or numeric, as the following example demonstrates:

Use theAscfunction and the relatedChrfunction to create rudimentary encryption methods.

Once you have obtained the character code for a particular character, you can perform calculations on this code to come up with a different number and then convert this to a character using theChrfunction. To decrypt your string, simply reverse the calculation. You may want to avoid character codes less than 20, however, since these can be interpreted as special nonprinting characters and cause undesirable effects if displayed or printed.

Asin Function

Class
System.Math

Syntax
Math.Asin(d)
d

Use: Required

Data Type: Double or any valid numeric expression

A number representing a sine, which can range from -1 to 1

Return Value
A Double between -pi/2 and pi/2 that is the arcsine ofdin radians

Description
Returns the arcsine ofd, in radians

Rules at a Glance

Ifdis out of range, the function returns NaN.

This is a Shared member, so it can be used without creating any objects.

Programming Tips and Gotchas
To convert from radians to degrees, multiply by 180/pi.

VB .NET/VB 6 Differences
TheAsinfunction did not exist in VB 6.

Atan Function

Class
System.Math

Syntax
Math.Atan(d)
d

Use: Required

Data Type: Double or any valid numeric expression

A number representing a tangent

Return Value
A Double that is the arctangent in radians ofd, in the range -pi/2 to pi/2

Description
Takes the ratio of two sides of a right triangle (d) and returns the corresponding angle in radians. Theratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.

Rules at a Glance

Ifdis out of range, the function returns NaN.

This is a Shared member, so it can be used without creating any objects.

Example

Programming Tips and Gotchas

To convert radians to degrees, multiply radians by 180/pi.

Do not confuseAtanwith the cotangent.Atanis the inversetrigonometricfunction ofTan, whereas the cotangent is the reciprocal of the tangent.

VB .NET/VB 6 Differences
TheAtanfunction corresponds to the VB 6Atnintrinsic function.

Atan2 Function

Class
System.Math

Syntax
Math.Atan2(y, x)
x

Use: RequiredPrivate Sub Main( )
Data Type: Double
The x coordinate of a point

y

Use: Required
Data Type: Double
The y coordinate of a point

Return Value
A Double that is the arctangent of theratiox/y, in radians

Description
Returns the angle in the Cartesian plane formed by the x-axis and a vector starting from the origin (0,0)and terminating at the point (x, y). More specifically, the return valueqsatisfies the following:

For (x, y) in quadrant 1, 0 < q < pi/2.

For (x, y) in quadrant 2, pi /2 < q < pi.

For ( x, y) in quadrant 3, -pi < q < -pi /2.

For ( x, y) in quadrant 4, -pi /2 < q < 0.

Rules at a Glance
This is a Shared member, so it can be used without creating any objects.

VB .NET/VB 6 Differences
TheAtan2function does not exist in VB 6.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

VB.NET Topics