2013-07-15 7 views
3

J'écris une application Windows Form dans .Net pour répertorier toutes les instances en cours d'exécution d'un logiciel de CAO/FAO tiers (dans ce cas CATIA) et laisser l'utilisateur en choisir une d'entre eux pour effectuer quelques tâches automatisées. Pour effectuer des tâches automatisées, j'ai besoin d'obtenir l'instance spécifique des objets COM - par rapport à Getobject() qui me donne une instance COM non spécifique. Est-il possible d'obtenir une instance COM spécifique en utilisant le handle de fenêtre ou d'autres méthodes? Comme l'a dit Raymond, il n'y a pas de solution unique pour tous les objets COM; mais je réussi à obtenir CATIA objets COM en utilisant le code suivant (qui utilise ROT pour remplir une liste avec tous CATIA COM Nom Instances):Obtention d'une instance spécifique d'objet COM dans VB.Net

<DllImport("user32.dll", CharSet:=CharSet.Auto)> Private Shared Sub GetClassName(ByVal hWnd As System.IntPtr, ByVal lpClassName As System.Text.StringBuilder, ByVal nMaxCount As Integer) End Sub 
<DllImport("ole32.dll", ExactSpelling:=True, PreserveSig:=False)> Private Shared Function GetRunningObjectTable(ByVal reserved As Int32) As IRunningObjectTable End Function 
<DllImport("ole32.dll", CharSet:=CharSet.Unicode, ExactSpelling:=True, PreserveSig:=False)> Private Shared Function CreateItemMoniker(ByVal lpszDelim As String, ByVal lpszItem As String) As IMoniker End Function 
<DllImport("ole32.dll", ExactSpelling:=True, PreserveSig:=False)> Private Shared Function CreateBindCtx(ByVal reserved As Integer) As IBindCtx End Function 

Try 

    Dim ROTObject As Object = Nothing 
    Dim runningObjectTable As IRunningObjectTable 
    Dim monikerEnumerator As IEnumMoniker = Nothing 
    Dim monikers(1) As IMoniker 

    runningObjectTable = GetRunningObjectTable(0) 
    runningObjectTable.EnumRunning(monikerEnumerator) 
    monikerEnumerator.Reset() 

    Dim numFetched As IntPtr = New IntPtr() 
    While (monikerEnumerator.Next(1, monikers, numFetched) = 0) 
     Dim ctx As IBindCtx 
     ctx = CreateBindCtx(0) 

     Dim runningObjectName As String = "" 
     monikers(0).GetDisplayName(ctx, Nothing, runningObjectName) 

     runningObjectName = runningObjectName.ToUpper 
     If (Not runningObjectName.Equals("")) Then 
      Dim runningObjectIns As Object = Nothing 
      runningObjectTable.GetObject(monikers(0), runningObjectIns) 

      'Check if object is a Catia object 
      Try 
       Dim catiaIns As INFITF.Application = Nothing 
       catiaIns = DirectCast(runningObjectIns, INFITF.Application) 
       ListCATIA.Items.Add(catiaIns.Windows.Count) 
      Catch Exc As Exception 
       MessageBox.Show(Exc.ToString()) 
      End Try 
     End If 
    End While 

Catch Exc As Exception 
    Throw Exc 
End Try 

Cependant, toutes les instances CATIA font référence à la première application CATIA chargée. Aucune idée pourquoi, quelqu'un?

+5

Il n'y a pas de solution générique. Vous devez voir si le serveur en question a une méthode pour énumérer des instances ou obtenir une instance spécifique. –

+0

@RaymondChen - Afin de supprimer cette question de la file d'attente sans réponse, j'ai déplacé votre commentaire dans une réponse wiki communautaire. Si vous souhaitez poster la réponse vous-même, s'il vous plaît laissez un commentaire sur le poste et je vais le supprimer. – JDB

Répondre

3

Le "problème" dans votre code est que l'appel GetObjecttoujours renvoie le premier serveur actif qu'il trouve dans le Running Object Table (ROT). L'énumération de la ROT ne change pas ce comportement et est un peu frustrante car elle montre qu'il y a plus d'un serveur dans la ROT. Notez que certains des éléments renvoyés dans l'énumération peuvent ne pas être en cours d'exécution: GetObject renvoie le premier serveur actif - pas nécessairement le premier renvoyé par l'énumération.

Cependant, dans le cas de CATIA en particulier, est possible pour obtenir une instance spécifique. Je soupçonne qu'il est possible avec de nombreuses applications si vous pouvez obtenir l'instance particulière d'intérêt pour exécuter du code, sur demande, avant vous obtenez réellement un pointeur vers l'instance COM.

Pour CATIA, ceci est une ébauche du processus que j'utilise:


1. Make a dll with two functions: 
    HRESULT __stdcall CoMarshalToFile(IUnknown* punk, const char* const filePath) 
    /* uses `::CreateStreamOnHGlobal`, `::CoMarshalInterface`, `::CoGetMarshalSizeMax`, 
    and `::GetHGlobalFromStream` to marshal the IUnknown to the specified file. 
    */ 
    HRESULT __stdcall CoMarshalFromFile(IUnknown** ppunk, const char* const filePath) 
    /* uses `::CreateStreamOnHGlobal` and `::CoUnmarshalInterface` to marshal 
    from the file to an IUnknown pointer. 
    */ 

2. In CATIA: 
    Note: this only needs to be done on the development computer. 
    Make a new "VBA projects" macro library. 
    Add "declare" statements for: 
     "LoadLibrary" (Windows API) 
     "CoMarshalToFile" (DLL specified above) 
    Add a function 
     Public Function MarshalCatiaToFile _ 
      (marshalInstanceFilePath As String, _ 
       marshalDllFolder As String) As Long 

    MarshalCatiaToFile calls "LoadLibrary" to load the C++ DLL 
    and then calls CoMarshalToFile (in DLL) to marshal the CATIA instance 
    to a file. 

    Remove the macro library from CATIA's list of macro libraries. 

3. Create a file: 
    "C:\Temp\CatiaOnTheFlyCatScripts\OnTheFlyCatScript.catvbs" 
    The file can be empty. 

4. In CATIA: 
     Note: this must be done for *each* user of CATIA on *each* computer used. 
     It may be possible to make this available to all users without individual 
     setup required: it is saved in "FrameUserAliases.CATSettings" 
     It may also be possible to reverse engineer the settings file and set up 
     the needed data from outside CATIA. 

    Add "C:\Temp\CatiaOnTheFlyCatScripts\" as a new "Directories" macro library. 
    Make the added library "current" 
    Use "Tools --> Customize --> Commands --> Macros" to assign a 
     "User Alias:" to the "OnTheFlyCatScript.catvbs" script file. 
     Name the alias "ExecuteOnTheFlyCatScript". 
    Remove the macro library from CATIA's list of macro libraries. 
    Close CATIA at this point to force the changes to be saved. 

5. VB.net/C# program: 
     Add the DLL (from step 1) and the CatVBA macro library (from step 2) as 
     "Embedded Resource" to the project. 

     During program execution: 
     Extract the DLL and macro library to an appropriate location. 
     Load the DLL into session using "LoadLibrary". 
     Create the file: 
      "C:\Temp\CatiaOnTheFlyCatScripts\OnTheFlyCatScript.catvbs" 

     The "OnTheFlyCatScript.catvbs" will be executed in CATIA. It 
      uses CATIA.SystemService.ExecuteScript to execute the 
      "MarshalCatiaToFile" function in the CatVBA macro library. 
      Add method of choice to this file to indicate success/failure. 
      I use a dialog box with the appropriate title. 

     To execute the "OnTheFlyCatScript.catvbs": 
      Using the Windows API functions, get the window handle for the 
      "Power Input" box at the bottom right of the "desired" 
      CATIA window. 
      Using the Windows API functions (*NOT* "SendKeys") send 
      "c:ExecuteOnTheFlyCatScript" + {Enter} to the "Power Input". 
      Wait for the "completion" signal from the script. If you used 
      a dialog box, use the Windows API function to close it. 

     Assuming the script succeeded in marshaling the CATIA instance to 
      a file, call the DLL function CoMarshalFromFile to get the CATIA 
      instance. 

Il est beaucoup de travail avec beaucoup de « mouvement » des pièces, mais il ne vous permet d'automatiser plusieurs sessions CATIA « simultanément ». Fonctionne bien pour mes besoins: extraction automatique de données à partir d'un ensemble de modèles CATIA et création automatique d'un ensemble de modèles CATIA en utilisant plusieurs sessions CATIA à la fois. Le goulot d'étranglement pour mon application est la session CATIA individuelle - pas de ressources CPU (en utilisant un processeur dual 4 ou 6 par processeur); l'ajout de plusieurs sessions améliore le débit.

Questions connexes