Índice de la sección dedicada a .NET (en el Guille) Cómo... en .NET

Simular el objeto APP de VB6

 

Publicado el 20/Sep/2003
Actualizado el 20/Sep/2003 (14/Dic/03)

 

Código para Visual Basic.NET (VB.NET)

Código para C Sharp (C#)

 

Introducción

En esta ocasión, el código que te voy a mostrar es cómo tener un objeto parecido al objeto APP de Visual Basic clásico.
Con ese objeto podemos acceder a cierta información sobre la aplicación que se está ejecutando, por ejemplo, para saber cual es el directorio del ejecutable, si ya está cargado el ejecutable en la memoria, además de datos de la versión del ejecutable y otros datos.

Hay una serie de propiedades que no se han convertido porque no tienen un equivalente más o menos directo en .NET, como por ejemplo: StartMode, ThreadId, etc. Esas propiedades las he dejado en la clase, aunque están comentadas para que no de la sensación que existen y no muestre un valor erróneo.

Si quieres saber los cambios en el objeto App de Visual Basic, puedes usar este link de la ayuda de Visual Studio .NET:
ms-help://.../vbcon/html/vxconchangestoappobjectinvisualbasicnet.htm

Para usar la clases cApp, que es la que nos servirá para simular el objeto App de VB6, habrá que crear una instancia indicando el ensamblado que se está ejecutando o bien el el tipo de la clase que está en ejecución, (recuerda que los formularios realmente son clases).

En las aplicaciones de consola, se tendrá que usar el constructor que recibe como parámetro un objeto del tipo Assembly:
En las aplicaciones de Windows se puede usar cualquiera de los dos constructores.
Aquí está la forma que habría que usar para ambos casos:

Usando el ensamblado que está en ejecución:
Dim App As New cApp(System.Reflection.Assembly.GetExecutingAssembly)

Usando el tipo del objeto que está en ejecución:
Dim App As New cApp(Me.GetType)

Esta sería la salida del proyecto de consola que he usado para probar la clase cApp:

Valores del objeto App:
-----------------------
App.EXEName = AppVB.exe
App.Path = E:\gsCodigo\VS.NET final\vb\AppVB\bin
App.Title = AppVB
App.FileDescription = AppVB (consola)
App.ProductName = revisión del 20/Sep/2003
App.Comments = Simulación de las propiedades del objeto APP de VB6
App.CompanyName = Guillermo -Nerja
App.LegalCopyright = cGuillermo 'guille' Som, 2001-2003
App.LegalTrademarks = Microsoft Visual Basic .NET
App.Major = 1
App.Minor = 0
App.Revision = 1358
App.HInstance = 285212672
App.PrevInstance = False

App.Build = 1358
App.FilePrivatePart = 25327
App.FileVersion = 1.0.1358.25327
App.Location = E:\gsCodigo\VS.NET final\vb\AppVB\bin\AppVB.exe


Pulsa INTRO para terminar.

Fíjate que si ejecutas dos veces el ejecutable, el valor de App.PrevInstance dará un resultado True (verdadero).

 

Para probarlo bien, tendrás que indicar algunos valores en el fichero AssemblyInfo correspondiente.

 

Espero que te sea de utilidad... y si no has trabajado antes con Visual Basic, decirte que seguramente no te parecerá útil, pero... aquí lo tienes por si lo necesitaras.

Nos vemos.
Guillermo

 


Código para Visual Basic.NET (VB.NET)

El código para VB .NET de la clase cApp y el módulo que se usará para crear la aplicación de consola.

'------------------------------------------------------------------------------
' cApp                                                              (07/Dic/01)
' Revisado y actualizado                                            (19/Sep/03)
'
' ©Guillermo 'guille' Som, 2001-2003
'------------------------------------------------------------------------------
'<member name="cApp" type="Class" >
'  <author name="Guillermo 'guille' Som" />
'  <date created="23/Nov/2001" updated="14/Dic/2001" revision="18/Sep/2003"/>
'  <summary>
'    Módulo para simular el objeto App de VB6, aunque sea parcialmente.
'  </summary>
'</member>
'------------------------------------------------------------------------------

Public Class cApp
    '' Evento para indicar que una propiedad no está disponible
    '' aunque se puede ampliar si se quieren capturar errores
    'Public Event ErrorMsg(ByVal PropertyName As String, ByVal sMessage As String)
    '
    Private mAssembly As System.Reflection.Assembly
    Private mLocation As String
    Private mFileVersionInfo As System.Diagnostics.FileVersionInfo
    '
    ' Al crear la clase hay que pasar forzosamente el tipo del Assembly a usar
    ' por ejemplo: Dim app As New cApp(Me.GetType)
    ' Este constructor es útil para aplicaciones de Windows o librerías (DLL)
    Public Sub New(ByVal theType As Type)
        Me.New(System.Reflection.Assembly.GetAssembly(theType))
    End Sub
    '
    ' Crear una nueva instancia usando un ensamblado.
    ' por ejemplo: Dim App As cApp = New cApp(System.Reflection.Assembly.GetExecutingAssembly)
    Public Sub New(ByVal theAssembly As System.Reflection.Assembly)
        mAssembly = theAssembly
        mLocation = mAssembly.Location
        mFileVersionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(mLocation)
    End Sub
    '
    Public ReadOnly Property Comments() As String
        Get
            Return mFileVersionInfo.Comments
        End Get
    End Property
    '
    Public ReadOnly Property CompanyName() As String
        Get
            Return mFileVersionInfo.CompanyName
        End Get
    End Property
    '
    Public ReadOnly Property EXEName() As String
        Get
            Return System.IO.Path.GetFileName(mLocation)
        End Get
    End Property
    '
    Public ReadOnly Property FileDescription() As String
        Get
            Return mFileVersionInfo.FileDescription
        End Get
    End Property
    '
    Public ReadOnly Property HInstance() As Int32
        Get
            Return System.Runtime.InteropServices.Marshal.GetHINSTANCE(mAssembly.GetModules()(0)).ToInt32
        End Get
    End Property
    '
    Public ReadOnly Property LegalCopyright() As String
        Get
            Return mFileVersionInfo.LegalCopyright
        End Get
    End Property
    '
    Public ReadOnly Property LegalTrademarks() As String
        Get
            Return mFileVersionInfo.LegalTrademarks
        End Get
    End Property
    '
    Public ReadOnly Property Major() As Int32
        Get
            Return Me.FileMajorPart
        End Get
    End Property
    '
    Public ReadOnly Property Minor() As Int32
        Get
            Return Me.FileMinorPart
        End Get
    End Property
    '
    Public ReadOnly Property Path(Optional ByVal conBackSlash As Boolean = False) As String
        Get
            If conBackSlash Then
                Return System.IO.Path.GetDirectoryName(mLocation) & "\"
            Else
                Return System.IO.Path.GetDirectoryName(mLocation)
            End If
        End Get
    End Property
    '
    Public ReadOnly Property PrevInstance() As Boolean
        Get
            Dim proceso As System.Diagnostics.Process
            '
            Return proceso.GetProcessesByName(proceso.GetCurrentProcess.ProcessName).GetUpperBound(0) > 0
        End Get
    End Property
    '
    Public ReadOnly Property ProductName() As String
        Get
            Return mFileVersionInfo.ProductName
        End Get
    End Property
    '
    Public ReadOnly Property Revision() As Int32
        Get
            Return Me.FileBuildPart
        End Get
    End Property
    '
    Public ReadOnly Property Title() As String
        Get
            Try
                Return mAssembly.GetName.Name
            Catch
                Return mFileVersionInfo.ProductName
            End Try
        End Get
    End Property
    '
    '--------------------------------------------------------------------------
    ' Estas propiedades no son parte del objeto App.
    '--------------------------------------------------------------------------
    '
    Public ReadOnly Property Build() As Int32
        Get
            Return Me.FileBuildPart
        End Get
    End Property
    Public ReadOnly Property FileBuildPart() As Int32
        Get
            Return mFileVersionInfo.FileBuildPart
        End Get
    End Property
    Public ReadOnly Property FileMajorPart() As Int32
        Get
            Return mFileVersionInfo.FileMajorPart
        End Get
    End Property
    Public ReadOnly Property FileMinorPart() As Int32
        Get
            Return mFileVersionInfo.FileMinorPart
        End Get
    End Property
    Public ReadOnly Property FilePrivatePart() As Int32
        Get
            Return mFileVersionInfo.FilePrivatePart
        End Get
    End Property
    Public ReadOnly Property FileVersion() As String
        Get
            Return mFileVersionInfo.FileVersion
        End Get
    End Property
    '
    ' Devuelve el valor del Location del Assemby usado              (09/Dic/01)
    Public ReadOnly Property Location() As String
        Get
            Return mLocation
        End Get
    End Property
    '--------------------------------------------------------------------------
    ' Fin de las propiedades que no son parte del objeto App
    '--------------------------------------------------------------------------
    '
    '--------------------------------------------------------------------------
    ' Las propiedades no disponibles
    '--------------------------------------------------------------------------
    'Public Property HelpFile() As String
    '    Get
    '        RaiseEvent ErrorMsg("HelpFile", "No equivalent. For more information, see Help Support Changes in Visual Basic .NET.")
    '        Return ""
    '    End Get
    '    Set(ByVal Value As String)
    '        '
    '        RaiseEvent ErrorMsg("HelpFile", "No equivalent. For more information, see Help Support Changes in Visual Basic .NET.")
    '    End Set
    'End Property
    'Public Property LogEvent() As String
    '    Get
    '        RaiseEvent ErrorMsg("LogEvent", "No equivalent. Logging in Visual Basic .NET is handled via Event Logs. For more information, see Creating and Removing Custom Event Logs.")
    '        Return ""
    '    End Get
    '    Set(ByVal Value As String)
    '        RaiseEvent ErrorMsg("LogEvent", "No equivalent. Logging in Visual Basic .NET is handled via Event Logs. For more information, see Creating and Removing Custom Event Logs.")
    '    End Set
    'End Property
    'Public Property LogMode() As String
    '    Get
    '        RaiseEvent ErrorMsg("LogMode", "No equivalent. Logging in Visual Basic .NET is handled via Event Logs. For more information, see Creating and Removing Custom Event Logs.")
    '        Return ""
    '    End Get
    '    Set(ByVal Value As String)
    '        RaiseEvent ErrorMsg("LogMode", "No equivalent. Logging in Visual Basic .NET is handled via Event Logs. For more information, see Creating and Removing Custom Event Logs.")
    '    End Set
    'End Property
    'Public Property LogPath() As String
    '    Get
    '        RaiseEvent ErrorMsg("LogPath", "No equivalent. Logging in Visual Basic .NET is handled via Event Logs. For more information, see Creating and Removing Custom Event Logs.")
    '        Return ""
    '    End Get
    '    Set(ByVal Value As String)
    '        RaiseEvent ErrorMsg("LogPath", "No equivalent. Logging in Visual Basic .NET is handled via Event Logs. For more information, see Creating and Removing Custom Event Logs.")
    '    End Set
    'End Property
    'Public NonModalAllowed As Boolean           'No equivalent. This was a read-only property related to ActiveX .dll files. The .NET common language runtime automatically manages this behavior. 
    'Public OleRequestPendingMsgText As String   'No equivalent. This property relates to OLE automation, which is not supported by Visual Basic .NET. 
    'Public OleRequestPendingMsgTitle As String  'No equivalent. This property relates to OLE automation, which is not supported by Visual Basic .NET. 
    'Public OleRequestPendingTimeout As Int32    'No equivalent. This property relates to OLE automation, which is not supported by Visual Basic .NET. 
    'Public OleServerBusyMsgText As String       'No equivalent. This property relates to OLE automation, which is not supported by Visual Basic .NET. 
    'Public OleServerBusyMsgTitle As String      'No equivalent. This property relates to OLE automation, which is not supported by Visual Basic .NET. 
    'Public OleServerBusyRaiseError As Boolean   'No equivalent. This property relates to OLE automation, which is not supported by Visual Basic .NET. 
    'Public OleServerBusyTimeout As Int32        'No equivalent. This property relates to OLE automation, which is not supported by Visual Basic .NET. 
    'Public RetainedProject As Object            'No equivalent. Visual Basic .NET does not have the ability to retain a project in memory. 
    'Public StartLogging As Int32                'No equivalent. Logging in Visual Basic .NET is handled via Event Logs. For more information, see Creating and Removing Custom Event Logs. 
    'Public StartMode As Int32                   'No equivalent. Logging in Visual Basic .NET is handled via Event Logs. For more information, see Creating and Removing Custom Event Logs. 
    'Public TaskVisible As Boolean               'No equivalent. For more information, see TaskVisible Property Changes in Visual Basic .NET. 
    'Public ThreadID As Int32                    'No equivalent. The threading model is different in Visual Basic .NET.  
    'Public UnattendedApp As Int32               'No equivalent. For unattended applications in Visual Basic .NET, choose a Console Application project. 
    '--------------------------------------------------------------------------
    ' Fin de las propiedades no disponibles
    '--------------------------------------------------------------------------
End Class

Este es el módulo a usar para crear la aplicación de consola que nos servirá para probar la clase cApp.
 


'------------------------------------------------------------------------------
' Prueba de la clase cApp para simular el objeto App de VB          (19/Sep/03)
'
' ©Guillermo 'guille' Som, 2003
'------------------------------------------------------------------------------
Option Strict On

Imports System

Module Module1
    Sub Main()
        Dim App As cApp = New cApp(System.Reflection.Assembly.GetExecutingAssembly)
        '
        Dim msg As String = _
            "Valores del objeto App:" & vbCrLf & _
            "-----------------------" & vbCrLf & _
            "App.EXEName         = " & App.EXEName & vbCrLf & _
            "App.Path            = " & App.Path & vbCrLf & _
            "App.Title           = " & App.Title & vbCrLf & _
            "App.FileDescription = " & App.FileDescription & vbCrLf & _
            "App.ProductName     = " & App.ProductName & vbCrLf & _
            "App.Comments        = " & App.Comments & vbCrLf & _
            "App.CompanyName     = " & App.CompanyName & vbCrLf & _
            "App.LegalCopyright  = " & App.LegalCopyright & vbCrLf & _
            "App.LegalTrademarks = " & App.LegalTrademarks & vbCrLf & _
            "App.Major           = " & App.Major.ToString & vbCrLf & _
            "App.Minor           = " & App.Minor.ToString & vbCrLf & _
            "App.Revision        = " & App.Revision.ToString & vbCrLf & _
            "App.HInstance       = " & App.HInstance.ToString & vbCrLf & _
            "App.PrevInstance    = " & App.PrevInstance.ToString & vbCrLf & _
            vbCrLf & _
            "App.Build           = " & App.Build.ToString & vbCrLf & _
            "App.FilePrivatePart = " & App.FilePrivatePart.ToString & vbCrLf & _
            "App.FileVersion     = " & App.FileVersion & vbCrLf & _
            "App.Location        = " & App.Location & vbCrLf
        '
        Console.WriteLine(msg)
        '
        Console.WriteLine()
        Console.WriteLine("Pulsa INTRO para terminar.")
        Console.ReadLine()
    End Sub
    '
    '' Esta forma se puede usar en VB para que el objeto esté siempre disponible,
    '' sobre todo si se usa en un módulo.
    'Public Function App() As cApp
    '    Return New cApp(System.Reflection.Assembly.GetExecutingAssembly)
    'End Function
End Module

 

 


Código para C Sharp (C#)

El código para C# de la clase cApp y la clase de prueba.

//-----------------------------------------------------------------------------
// cApp                                                                (07/Dic/01)
// Revisado y actualizado                                            (19/Sep/03)
//
// ©Guillermo 'guille' Som, 2001-2003
//-----------------------------------------------------------------------------
using System;

namespace AppCS
{
    /// 
    /// Descripción breve de cApp.
    /// 
    //
    public class cApp
    {
        //
        private System.Reflection.Assembly mAssembly;
        private string mLocation;
        private System.Diagnostics.FileVersionInfo mFileVersionInfo;
        //
        // Al crear la clase hay que pasar forzosamente el tipo del Assembly a usar
        // por ejemplo: cApp App = new cApp(this.GetType)
        // Este constructor es útil para aplicaciones de Windows o librerías (DLL)
        public cApp(Type theType)
        {
            mAssembly = System.Reflection.Assembly.GetAssembly(theType);
            mLocation = mAssembly.Location;
            mFileVersionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(mLocation);
        }  
        //
        // Crear una nueva instancia usando un ensamblado.
        // por ejemplo: cApp App = new cApp(System.Reflection.Assembly.GetExecutingAssembly())
        public cApp(System.Reflection.Assembly theAssembly)
        {
            mAssembly = theAssembly;
            mLocation = mAssembly.Location;
            mFileVersionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(mLocation);
        }  
        //
        public string Comments
        {
            get
            {
                return mFileVersionInfo.Comments;
            }
        }  
        //
        public string CompanyName
        {
            get
            {
                return mFileVersionInfo.CompanyName;
            }
        }  
        //
        public string EXEName
        {
            get
            {
                return System.IO.Path.GetFileName(mLocation);
            }
        }  
        //
        public string FileDescription
        {
            get
            {
                return mFileVersionInfo.FileDescription;
            }
        }  
        //
        public Int32 HInstance
        {
            get
            {
                 return System.Runtime.InteropServices.Marshal.GetHINSTANCE(mAssembly.GetModules()[0]).ToInt32();
             }
        }  
        //
        public string LegalCopyright
        {
            get
            {
                return mFileVersionInfo.LegalCopyright;
            }
        }  
        //
        public string LegalTrademarks
        {
            get
            {
                return mFileVersionInfo.LegalTrademarks;
            }
        }  
        //
        public Int32 Major
        {
            get
            {
                 return this.FileMajorPart;
             }
        }  
        //
        public Int32 Minor
        {
            get
            {
                 return this.FileMinorPart;
             }
        }  
        //
        public string Path()
        {
            return System.IO.Path.GetDirectoryName(mLocation);
        }
        public string Path(bool conBackSlash)
        {
            if( conBackSlash )
                return System.IO.Path.GetDirectoryName(mLocation) + @"\";
            else
                return System.IO.Path.GetDirectoryName(mLocation);
        }  
        //
        public bool PrevInstance
        {
            get
            {
                return System.Diagnostics.Process.GetProcessesByName(System.Diagnostics.Process.GetCurrentProcess().ProcessName).GetUpperBound(0) > 0;
            }
        }  
        //
        public string ProductName
        {
            get
            {
                return mFileVersionInfo.ProductName;
            }
        }  
        //
        public Int32 Revision
        {
            get
            {
                return this.FileBuildPart;
             }
        }  
        //
        public string Title
        {
            get
            {
                try
                {
                    return mAssembly.GetName().Name;
                }
                catch
                {
                    return mFileVersionInfo.ProductName;
                }
            }
        }  
        //
        public Int32 Build
        {
            get
            {
                 return this.FileBuildPart;
             }
        }  
        public Int32 FileBuildPart
        {
            get
            {
                 return mFileVersionInfo.FileBuildPart;
             }
        }  
        public Int32 FileMajorPart
        {
            get
            {
                 return mFileVersionInfo.FileMajorPart;
             }
        }  
        public Int32 FileMinorPart
        {
            get
            {
                 return mFileVersionInfo.FileMinorPart;
             }
        }  
        public Int32 FilePrivatePart
        {
            get
            {
                 return mFileVersionInfo.FilePrivatePart;
             }
        }  
        public string FileVersion
        {
            get
            {
                return mFileVersionInfo.FileVersion;
            }
        }  
        //
        public string Location
        {
            get
            {
                return mLocation;
            }
        }  
        //--------------------------------------------------------------------------
        // Fin de las propiedades que no son parte del objeto App
        //--------------------------------------------------------------------------
    }
}
 

Esta clase será la que se usará para probar la clase cApp:


//-----------------------------------------------------------------------------
// Prueba de la clase cApp para simular el objeto App de VB         (19/Sep/03)
//
// ©Guillermo 'guille' Som, 2003
//-----------------------------------------------------------------------------
using System;

namespace AppCS
{
    /// 
    /// Descripción breve de Class1.
    /// 
    class Class1
    {
        /// 
        /// Punto de entrada principal de la aplicación.
        /// 
        [STAThread]
        static void Main(string[] args)
        {
            //
            // TODO: agregar aquí código para iniciar la aplicación
            //
            cApp App = new cApp(System.Reflection.Assembly.GetExecutingAssembly());
            //
            string msg  =
                "Valores del objeto App:" + Console.Out.NewLine +
                "-----------------------" + Console.Out.NewLine +
                "App.EXEName         = " + App.EXEName + Console.Out.NewLine +
                "App.Path            = " + App.Path() + Console.Out.NewLine +
                "App.Title           = " + App.Title + Console.Out.NewLine +
                "App.FileDescription = " + App.FileDescription + Console.Out.NewLine +
                "App.ProductName     = " + App.ProductName + Console.Out.NewLine +
                "App.Comments        = " + App.Comments + Console.Out.NewLine +
                "App.CompanyName     = " + App.CompanyName + Console.Out.NewLine +
                "App.LegalCopyright  = " + App.LegalCopyright + Console.Out.NewLine +
                "App.LegalTrademarks = " + App.LegalTrademarks + Console.Out.NewLine +
                "App.Major           = " + App.Major.ToString() + Console.Out.NewLine +
                "App.Minor           = " + App.Minor.ToString() + Console.Out.NewLine +
                "App.Revision        = " + App.Revision.ToString() + Console.Out.NewLine +
                "App.HInstance       = " + App.HInstance.ToString() + Console.Out.NewLine +
                "App.PrevInstance    = " + App.PrevInstance.ToString() + Console.Out.NewLine +
                Console.Out.NewLine +
                "App.Build           = " + App.Build.ToString() + Console.Out.NewLine +
                "App.FilePrivatePart = " + App.FilePrivatePart.ToString() + Console.Out.NewLine +
                "App.FileVersion     = " + App.FileVersion + Console.Out.NewLine +
                "App.Location        = " + App.Location + Console.Out.NewLine;
            //
            Console.WriteLine(msg);
            //
            Console.WriteLine();
            Console.WriteLine("Pulsa INTRO para terminar.");
            Console.ReadLine();
        }
    }
}

 


la Luna del Guille o... el Guille que está en la Luna... tanto monta...