开发者

Exited event of Process is not rised?

In my appliation,I am opening an excel sheet to show one of my Excel documents to the user.But before s开发者_高级运维howing the excel I am saving it to a folder in my local machine which in fact will be used for showwing.

While the user closes the application I wish to close the opened excel files and delete all the excel files which are present in my local folder.For this, in the logout event I have written code to close all the opened files like 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 process exited event I wish to delete the excel file whose process is been exited like 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 this exited event is not called at all.On the other hand if I delete the file after closing the MainWindow of the process I am getting an exception "File already used by another process".

Could any help me on how to achieve my objective or give me an reason why the process exited event is not being called?


You should try Dynami's suggestion, but you may also need to set 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();
    }                       
}


It isn't that likely that your code will find the proper window. Excel is a single-instance app, it will open additional windows for each spreadsheet if you start it more than once. You'll at a minimum have to iterate the windows it has open by P/Invoking EnumWindows and getting their title with GetWindowText.


Have you tried to reverse those two lines :

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

Such that the event is registered before the system tries to get rid of it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜