0

Я новичок в VB.net, и я пытаюсь написать приложение форм, которое работает с Autodesk Inventor.Как убить процесс, который не имеет окон в VB.net?

К сожалению, каждый раз, когда я закрываю Inventor, процесс «Inventor.exe» по-прежнему остается. Я не понимал этого во время отладки, и я это осознал, когда проверил диспетчер задач после того, как вся система начала отставать. Убивание каждого процесса с тем же именем довольно просто, но проблема в том, что у конечного пользователя могут быть отдельные документы открытыми в другом окне Inventor. Поэтому мне нужно написать функцию, которая только убивает процессы Inventor, у которых нет открытого окна.

Public Class Form1 
    Dim _invApp As Inventor.Application 
    Dim _started As Boolean = False 
    Public Sub New() 

    ' This call is required by the designer. 
    InitializeComponent() 

    ' Add any initialization after the InitializeComponent() call. 
    Try 
     _invApp = Marshal.GetActiveObject("Inventor.Application") 

    Catch ex As Exception 
     Try 
      Dim invAppType As Type = _ 
       GetTypeFromProgID("Inventor.Application") 

      _invApp = CreateInstance(invAppType) 
      _invApp.Visible = True 

      'Note: if you shut down the Inventor session that was started 
      'this(way) there is still an Inventor.exe running. We will use 
      'this Boolean to test whether or not the Inventor App will 
      'need to be shut down. 
      _started = True 

     Catch ex2 As Exception 
      MsgBox(ex2.ToString()) 
      MsgBox("Unable to get or start Inventor") 
     End Try 
    End Try 

End Sub 

Другой раздел, где я запускаю процесс, который представляет собой конкретный файл 3D-модели.

Public Sub SaveAs(oTemplate As String) 
    'define the active document 
    Dim oPartDoc As PartDocument = _invApp.ActiveDocument 
    'create a file dialog box 
    Dim oFileDlg As Inventor.FileDialog = Nothing 
    Dim oInitialPath As String = System.IO.Path.GetFullPath("TemplatesResources\" & oTemplate) 
    _invApp.CreateFileDialog(oFileDlg) 

    'check file type and set dialog filter 
    If oPartDoc.DocumentType = kPartDocumentObject Then 
     oFileDlg.Filter = "Autodesk Inventor Part Files (*.ipt)|*.ipt" 
    ElseIf oPartDoc.DocumentType = kAssemblyDocumentObject Then 
     oFileDlg.Filter = "Autodesk Inventor Assembly Files (*.iam)|*.iam" 
    ElseIf oPartDoc.DocumentType = kDrawingDocumentObject Then 
     oFileDlg.Filter = "Autodesk Inventor Drawing Files (*.idw)|*.idw" 
    End If 

    If oPartDoc.DocumentType = kAssemblyDocumentObject Then 
     oFileDlg.Filter = "Autodesk Inventor Assembly Files (*.iam)|*.iam" 
    End If 

    'set the directory to open the dialog at 
    oFileDlg.InitialDirectory = "C:\Vault WorkSpace\Draft" 
    'set the file name string to use in the input box 
    oFileDlg.FileName = "######[email protected]@" 

    'work with an error created by the user backing out of the save 
    oFileDlg.CancelError = True 
    On Error Resume Next 
    'specify the file dialog as a save dialog (rather than a open dialog) 
    oFileDlg.ShowSave() 

    'catch an empty string in the imput 
    If Err.Number <> 0 Then 
     MessageBox.Show("Any changes made from here will affect the original template file!", "WARNING", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification) 
    ElseIf oFileDlg.FileName <> "" Then 
     Dim MyFile As String = oFileDlg.FileName 
     'save the file 
     oPartDoc.SaveAs(MyFile, False) 
     'open the drawing document 
     System.Diagnostics.Process.Start(oInitialPath & ".idw") 
     Dim oFinalPath As String = oPartDoc.FullFileName 
     MessageBox.Show(oFinalPath, "", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification) 
     MessageBox.Show("Loaded", "", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification) 
     Dim oDrawingDoc As DrawingDocument = _invApp.Documents.ItemByName(oInitialPath & ".idw") 
     'oDrawingDoc.SaveAs() 

    End If 
End Sub 

Любая помощь приветствуется. Благодаря

+1

Лучше пытаться понять, почему ваш процесс не прекращается, когда ваш пользователь закрывает его, – Steve

+0

Когда моя форма открывается он открывает изобретателя. Я скопировал код из другого места. Я разместил его выше, как Public Sub New(). Я также отправлю часть своего кода, где я запускаю другой процесс, который открывает конкретный файл для изобретателя. – RBuntu

+1

Я не вижу, где вы располагаете объект Inventor.Application. Может ли это быть проблема? – OneFineDay

ответ

1

В конце на вашей форме, вероятно, FormClosed, добавьте следующее:

Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed 
    If (_invApp Is Nothing) Then Return ' if empty, then no action needed 
    _invApp.Quit() 
    Marshal.ReleaseComObject(_invApp) 
    _invApp = Nothing 
    System.GC.WaitForPendingFinalizers() 
    System.GC.Collect() 
    End Sub 

Это должно сделать релиз .NET и правильно расположить COM-объект для Inventor.

И рассмотрим объявить переменную Inventor и назначить Nothing/нуль, это безопаснее (избежать ошибок)

Dim _invApp As Inventor.Application = Nothing 
+0

Это, похоже, не работает для меня. Вот что я использую. http://pastebin.com/QK9Jb6ND – RBuntu

+0

Извините, что я забыл Close() перед ReleaseasseComObject. В основном вам нужно закрыть приложение, а затем сказать ему, что он вам больше не нужен (релиз) –

+0

Но разве это не означает, что форма закрывается сама по себе? Я только хочу, чтобы программа убила любые «inventor.exe» процессы, у которых нет окна. И я хочу, чтобы программа выполнялась только тогда, когда пользователь закрыл ее вручную. – RBuntu

Смежные вопросы