Multiple WinWord in Task Manager - c#

my c# application creates winword in task manager and close properly from taskmanager. but in case my application crashed then the winword remains opened in task manager and cannot able to process those word document.
so in that case i want to kill those winword alone which is created by my application and not all.
please help to finish this.

When instances of winword.exe are created through interop, they'll have the string "/Automation -Embedding" included in the process command line.
So, if you want to manually kill only your interop winword processes, without killing any user-initiated instances of Microsoft Word, you can open up Mark Russinovich's free ProcessExplorer utility, right click on a line with winword.exe, choose "properties", and look at the command line (in the Image tab). If you see the /Automation switch, you'll know it's an interop process and you can kill it. Here's how the interop winword.exe will look in ProcessExplorer:

Try the following:
try
{
// open your word document
// process your word document
}
catch
{
// handle any errors (e.g. provide error messages
}
finally
{
// close the word document properly
}
To prevent orphaned word processes you will need to store the open processes in a central way in your application and close all remaining processes before shutting down the application. Furthermore you could register to the unhandled error event and then close all processes if that happens.
Shutting down word processes if you cannot open a document is no option in most cases, because that document might be opened for editing in a "real" word instance.

Related

C# After opening an excel workbook, how can I prevent a user from opening another excel file(via windows) in the same excel instance?

I have created a program that searches excel, word, and txt files for a user entered string. So I open each file, search for the string, and add the file(with info) to a datagrid if the document contains this string.
The program works great, except for some unforseen situations. If the user did not have excel open when they start the search, the program opens a new instance of excel and begins searching. During this search, if the user then opens an excel file from windows explorer, it will open it in the same instance that my program is using, which then proceeds to show all the files it is opening, searching, then closing.
If the user already has excel open, then my program opens it's own instance and there is no issue. The exact same issue applies to word documents as well.
My question is, how can I prevent the user from opening a file in the same instance of excel that my program is currently using?
Here are the basics of how I am accessing excel:
using Excel = Microsoft.Office.Interop.Excel;
Excel.Application xlsApp = new Excel.Application();
Excel.Workbook wkb = null;
Excel.Workbooks wkbs = xlsApp.Workbooks;
xlsApp.DisplayAlerts = false;
wkb = wkbs.Open(filePath, ReadOnly: true);
//Do search here...
//Close the workbook when necessary...
wkb.Close(false);
//Close the app when necessary...
xlsApp.Quit();
I'm hoping there's some parameter I can set to prevent the user from opening documents in the same instance.
Not sure if you are still looking for a solution to this problem after all this time. I have been trying to solve this issue myself and with help from the guys at Add-In Express I have come up with a workable solution. The following should work for you.
Create your Word/Excel instance with ckNewInstance.
Open a new document/workbook
Close it.
Open the document/workbook you intend to work with.
This will normally stop any documents/workbooks being opened via your instance when the user opens via shortcut.
But sometimes this fails (eg if there are left over instances of Word in processes).
To make my instance of Word "exclusive" I am currently doing the following (until something better comes along):
Opening a dummy document as explained above.
Disable all functionality within Word which allows for opening of documents.
Just in case 1 fails try and catch any documents opened by my instance of Word and close them.
The last part of the process is kludgy, but I can't see any other way around it.
Originally, I used DocumentOpen and DocumentNew events to catch document opening and new documents and this works well. You can close the documents in these events and reopen them without apparent issue.
However, further testing showed that DocumentOpen and DocumentNew events only fire if the document is opened using your Word instance ie if the user uses the backstage for example. If they click on a Word shortcut, even though the document opens in your instance, it does not (why ever not MS?) fire the above events.
The only way I can find to capture Word documents opened by whatever means is to use the DocumentChange event and loop through each document and if it isn't the one I want, close it and reopen it.
Unfortunately, this does not work in a straightforward manner. It seems to work okay for new documents, but if the user opens an existing document and you attempt to close it in the DocumentChange event, it causes your principal document to hang (at least it does for me).
To get around this I use the DocumentChange event to find the offending docs and fire off a timer (100 ms seems to do the trick) to handle the actual closing and opening.
All in all utterly horrible and I wish someone will come back and tell me that I have wasted days on the above because Office applications have a "MakeMyInstanceUnique" property which does exactly what I need!

In Visio Addin, the API method Application.Documents.OpenEx() throw exception after opening several files (one after the other and not in parallel)

I'm trying to open some files(between 50-400) in programmatically way by Add-in in orde to edit them.
I do this in sequential way, open one, edited, closed and so on.
Sometimes, in unexpected behavior, the OpenEx () method throws an system.accessviolationexception and the program stop, I can't clear the file that the program is trying to open and canot cancel the requst to open and move on.
I can catch the exception, but once it happens with a particular file then also trying to open all the following files throws an exception.
I would like to ask:
1. Why does this sometimes happen inconsistently?
2. Is there a way to cancel the file opening request? Does memory need / can be cleared? What do I need to do so that I can open files after it happens with some file?
This is the main code:
Globals.ThisAddIn.Application.Documents.OpenEx(currVisioFile,(int)Microsoft.Office.Interop.Visio.VisOpenSaveArgs.visOpenRW);
If opening a lot of files from the Visio add-in itself is or becomes unstable (issue I've been facing as well), I recommend opening and closing a new instance of Visio for each document you have.
A way to do that in Python for example is to install the pypiwin32 package and then run the following script:
import win32com.client
documentsToProcess = ["path/to/doc1", "path/to/doc2", "path/to/doc3"]
for path in documentsToProcess:
app = win32com.client.DispatchEx("Visio.Application") # Open new Visio instance
doc = app.Documents.Open(path) # Open your document (and hopefully blocks)
doc.Saved = true # For quiet exit
app.Quit()
You can find all official documentation about the Open function and all others objects and methods here.
Then you would change your add-in code so that it just waits for a document to be opened before processing it, like this:
private void ThisAddIn_Startup(object sender, System.EventArgs e) {
// We subscribe to the DocumentOpened/Created event
this.Application.DocumentOpened += Application_DocumentOpened;
}
private void Application_DocumentOpened(Document doc) {
// Process your document here.
// Do your work on your document here!
}
Usually the work you have to do on each document is much longer than just creating a new instance of Visio so it shouldn't be an issue.
Maybe you need to make a few changes to ensure that the Visio instance closes correctly but that's the idea. You could also force kill the process if needed when it gets stuck.

How to wait for a task to finish

I've got a Windows Form, where I've got a report being exported to PDF format.
After the report is generated, I would like to have the application terminated completely. I have added an Application.Exit() clause, however this sometimes closes the process while exporting is still happening.
Hence, I would like to close the application only if the exporting is complete.
I have tried the following:
while(true)
{
if (Process.GetCurrentProcess().WaitForInputIdle())
{
Application.Exit();
}
}
and also:
while(true)
{
if (Process.GetCurrentProcess().Responding)
{
Application.Exit();
}
}
None have worked however - the application still sometimes closes before the export is complete.
What am I doing wrong?
You could start exporting in another process and wait for it to finish (check out the related post: Wait till a process ends).
If you don't want that, you can check whether the file to which the exporting is done exists and whether it is locked (check out Wait Until File Is Completely Written).
The problem is that if the application is designed to be responsive to user interactions, both ways will close the application even though it is still working.
Maybe you should monitor the output of the application? That is: If the PDF file is present, the process is done. Or rather: If the PDF file is present and hasn't been modified for 15 seconds or something, exit the application.

Prompt message while trying to open an excel file

I have a code that open an Excel file and read the content. Each time i run the code for the first time, it opens the Excel file without prompting me. But from the second time going it always prompt me this message
TestFile.xlsx is being modified by user 1. Open as read only
and it always prompt at this portion of the code:
Excel ._Workbook xlsBook = xlsApp .Workbooks.Open (_fileName,0,false,5 ,"","",false ,Excel .XlPlatform .xlWindows ,"",true ,false ,0,true ,false ,false );
NB: i also close the file after the operation done and also using VS 2012
So what can be the problem of this prompt ??
After running your Code and exiting, look in the taskmanager, most likely die EXCEL.EXE instance is still running.
you most likely didn't release all the com objects like:
System.Runtime.InteropServices.Marshal.ReleaseComObject(_theWorkbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(_sheets);
System.Runtime.InteropServices.Marshal.ReleaseComObject(_workSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(_range);
System.Runtime.InteropServices.Marshal.ReleaseComObject(_excelObj);
Make sure there are no resources where the file would be still opened. Could you post the code you're using to close the resource? Perhaps there's an error there.
Finally, as ugly as it is, it's valid for testing purposes: try manually calling the garbage collector after closing the file.
FINALLY, consider using the OpenXml API to work with Excel/Word files, as opposed to the Interop DLLs (remember these require the client to have Excel installed, as opposed to the OpenXml libraries which you can deploy with your application).

Tracking multiple processes at same time

I have an application (winforms) that downloads a file to user's temporary folder, then it opens the file for user to see contents, and when the file is closed, the file gets deleted from temp folder. The application is working ok if I open let's say one .pdf and one .doc The problem appears when trying to open one .doc if another winword process is still runing (doesn't matter if is opened by my app or directly by user).
I'm using the following code:
_OpenFileProces = System.Diagnostics.Process.Start(TempFileName);
_OpenFileProces.EnableRaisingEvents = true;
_OpenFileProces.Exited += new EventHandler(_OpenFileProces_Exited);
and this one to clear temp
void _OpenFileProces_Exited(object sender, EventArgs e)
{
string s = ((System.Diagnostics.Process)sender).StartInfo.FileName;
System.IO.File.Delete(s);
}
It seems that the running process is stopping my own.. and due to stopping it will delete the file or it will generate an error while trying to delete the file.
Do you have any suggestion how can I open my own process? The thing is I do not know what file type I have to open (it could be anything) and I'm counting on windows to choose the best application. from my test, notepad works ok, but winword and acrobat closes my process.
Thank you
I suspect that Microsoft Word is doing exactly the same thing here as Raymond Chen describes the Windows Shell as doing here:
A customer wanted help with monitoring the lifetime of an Explorer window.
"We want to launch a copy of Explorer to open a specific folder, then wait until the user closes the folder before continuing. We tried launching a copy of Explorer with the folder on the command line, then doing a Wait­For­Single­Object on the process handle, but the wait sometimes completes immediately without waiting. How do we wait until the user closes the Explorer window?"
This is another case of solving a problem halfway and then having trouble with the other half.
The reason that Wait­For­Single­Object returns immediately is that Explorer is a single-instance program (well, limited-instance). When you open an Explorer window, the request is handed off to a running copy of Explorer, and the copy of Explorer you launched exits. That's why your Wait­For­Single­Object returns immediately.
In your case, Word is already running, so when you create a second Word process and instruct it to open your document, it simply hands the request off to the instance of Word that is already running, and quits the second process you launched immediately.
That's what you're seeing when you describe that "the running process is stopping my own". Because that second instance gets closed immediately after you launch it, the Exited event is raised and your code tells it to delete the file!
You astutely observe that Notepad (unlike Word and Adobe Acrobat) works just fine. That's because Notepad is designed to be a multiple-instance application. You can open as many copies of Notepad as you want; it doesn't care if there's already 1 or 6 copies open on the desktop. And more importantly, asking the shell to open a text document in Notepad actually opens a second copy of the Notepad application, rather than sending a request to the first instance to open a new window for the new doc.
You should set the Process.StartInfo.UseShellExecute to true like this _OpenFileProces.StartInfo.UseShellExecute = true; before starting the process and then it should work I think...

Categories

Resources