Passing Enums - QTP

The following code in a .NET module displays a .NET form on the center of the screen:

'Create a new Form
Dim oForm as System.Windows.Forms.
*Form = New oForm
'Center the from on the screen
oForm.StartPosition = FormStartPosition.CenterScreen

But we can't use this code in QTP because we do not have access to the FormStartPosition. CenterScreen .NET constant. To develop a solution we need to see how the EnumFormStartPositionis defined in .NET:
'Definition of FormStartPosition in .NET Public EnumFormStartPosition.

' Fields
CenterParent = 4
CenterScreen = 1
Manual = 0
WindowsDefaultBounds = 3
WindowsDefaultLocation = 2
End Enum

Now that we know that the CenterScreen constant has a Value 1, we can try to execute the following code in QTP to assign the StartPosition:

'Create a .NET Form object
Set oForm = DotNetFactory("System.Windows,Forms,Form")
ConstCenterScreen = 1
oForm.StartPosition = CenterScreen

But attempting to execute the code given above throws the following exception:

External object System.Windows.Forms.Form::StartPosition has thrown the following exception:

Method 'System.Windows.Forms.Form.StartPosition' not found.

This exception occurs because in .NET everything is an object and that includes enum values. So when we attempt to assign a numeric value, the conversion from numeric to enum object does not occur and hence we get an exception. But we can use a workaround here; we know that everything is an object in .NET which means if we use the StartPosition property on right side of an assignment we get the needed Enum object:

'Create a .NET Form object
Set oForm = DotNetFactory("System.Windows.Forms,Form")
'Get the enumFormStartPosition
Set StartPosition = oForm.StartPosition
oForm.StartPosition = StartPosition.CenterScreen

The above technique works by first getting the StartPosition object which is of Type System. W ndows.Forms.FormStartPosition. So whenever we need to pass a .Net enum object to a function, we should try to find a property that is a child of another object which returns the required data type.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

QTP Topics