In VB.NET check for changes in a file launched with process.start()

后端 未结 3 1900
春和景丽
春和景丽 2021-01-28 16:59

I\'m developing a vbnet/c#.NET based application that opens files with different applications(excel, word, etc).

The application is launched using Dim app As Proce

相关标签:
3条回答
  • 2021-01-28 17:15

    You can achieve behaviour close to what you require by calling Process.CloseMainWindow rather than Process.Kill.

    The behavior of CloseMainWindow is identical to that of a user closing an application's main window using the system menu. Therefore, the request to exit the process by closing the main window does not force the application to quit immediately.

    Data edited by the process or resources allocated to the process can be lost if you call Kill. Kill causes an abnormal process termination, and should be used only when necessary. CloseMainWindow enables an orderly termination of the process and closes all windows, so it is preferable for applications with an interface.

    In the case of Office applications with unsaved changes, CloseMainWindow would launch the Save dialog. You would need to handle scenarios where the users presses “Cancel”, since that may result in the WaitForExit call blocking indefinitely.

    For example:

    // Launch Word application.
    Process wordProcess = 
        Process.Start(@"C:\Program Files (x86)\Microsoft Office\Office12\winword.exe");
    
    // Give user some time to type in text.
    Thread.Sleep(TimeSpan.FromSeconds(20));
    
    // Request Word to close.
    wordProcess.CloseMainWindow();
    
    // Wait until user saves or discards changes.
    // May block indefinitely if user cancels.
    wordProcess.WaitForExit();
    
    0 讨论(0)
  • 2021-01-28 17:32

    For office applications use Office Interop Assemblies, not Process.Start to start and control them. Here is an example code for Excel (in VB.NET). You should add Microsoft.Office.Interop.Excel.dll to the project references in order for this to work.

       oExcel = New Microsof.Office.Interop.Excel.Application
       oBook = oExcel.Workbooks.Open(filepath)
       'Do your stuff
       oBook.Close 'This will trigger the application native prompt if the document was modified
       oExcel.Quit()
    

    For other programs it depends much on a program

    0 讨论(0)
  • 2021-01-28 17:32

    There are different approaches for this problem. You can calculate some sort of initial check-sum and see whether your document has any changes by redoing the check-sum and comparing against the original one.

    This part is not very clear from your question, If the document gets saved, probably you can look at the date_modified value of the file to see whether there has been any modifications.

    0 讨论(0)
提交回复
热议问题