Quit the process is not called?

In my application, I open an excel sheet to display one of my Excel documents to the user. But before showing excel, I save it in a folder on my local machine, which will actually be used for showwing.

While the user is closing the application, I want to close the open excel files and delete all the excel files that are in my local folder. To do this, in the logout event, I wrote code to close all open files, as shown below,

Process[] processes = Process.GetProcessesByName(fileType);

                foreach (Process p in processes)
                {

                    IntPtr pFoundWindow = p.MainWindowHandle;
                    if (p.MainWindowTitle.Contains(documentName))
                    {
                        p.CloseMainWindow();
                        p.Exited += new EventHandler(p_Exited);                            
                    }                       
                }

And in the completed process, I want to delete the excel file whose process is completed, as shown below

void p_Exited(object sender, EventArgs e)
    {
        string file = strOriginalPath;
        if (File.Exists(file))
        {
            //Pdf issue fix
            FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
            fs.Flush();
            fs.Close();
            fs.Dispose();
            File.Delete(file);
        }
    }

But the problem is that this outgoing event is not called at all. On the other hand, if I delete a file after closing the MainWindow process, I get an exception "The file is already being used by another process."

- , , , ?

+3
3

Dynami, Process.EnableRaisingEvents = true.

Process[] processes = Process.GetProcessesByName(fileType);

foreach (Process p in processes)
{
    IntPtr pFoundWindow = p.MainWindowHandle;
    if (p.MainWindowTitle.Contains(documentName))
    {
        p.EnableRaisingEvents = true;
        p.Exited += new EventHandler(p_Exited);
        p.CloseMainWindow();
    }                       
}
+2

, . Excel - , , . , , , P/Invoking EnumWindows, GetWindowText.

+2

:

if (p.MainWindowTitle.Contains(documentName))
{
    p.Exited += new EventHandler(p_Exited); 
    p.CloseMainWindow();                           
}

, , ?

+1

Source: https://habr.com/ru/post/1737353/


All Articles