问题
I am trying to print pdf, ppt, and word documents from my windows service using ShellExecute.
Process printingProcess = new Process
{
StartInfo =
{
FileName = filePath,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = true,
Verb = "Print"
}
};
printingProcess.Start();
This works in most cases. But for word documents that are corrupt, the Process.Start method never completes and the service hangs.
Basically, word pops up the "bad document! repair" dialog. I want the service to identify that word is not playing nice and kill the process and proceed with the next document in its queue.
What should I do?
[UPDATE]
Guys, here is the code to reproduce the issue:
static void Main(string[] args)
{
string filePath = @"d:\corruptdocument.docx";
PrintDocument(filePath);
Console.WriteLine("Completed!");
Console.ReadKey();
}
private static void PrintDocument(string filePath)
{
Process printingProcess = new Process
{
StartInfo =
{
FileName = filePath,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = true,
Verb = "Print"
}
};
using (printingProcess)
{
Console.WriteLine("Starting process...");
printingProcess.Start();
Console.WriteLine("Completed start...");
}
}
And here is a screenshot : http://twitpic.com/23jwor
回答1:
Nah, that cannot be accurate. Neither ShellExecuteEx nor CreateProcess can block. It is surely the next statement in your code, the one you didn't post. I'd guess at Process.WaitForExit(). Note that it has an overload that accepts a timeout.
Not that it will work reliably, Word is a single-instance process. Using Microsoft.Office.Interop.Word is the better mousetrap. The Application.Document.Open() method accepts an OpenAndRepair argument.
回答2:
try adding the /q and /x command-line switches to your StartInfo.
Via MS documentation, those switches start Word in quiet mode (/q), and respond to one DDE request (you may try omitting the /x)
回答3:
Okay Guyz, here is what I found out!
ShellExecute for word uses DDE. So the process.Start() method returns only after the command is complete (in my case, "printing the document"). [Not sure if this is accurate, but atleast that is my experience with word]
So what are our options?
- As @Hans mentioned, use COM interop.
- Run the printing job in a seperate thread and wait for the thread to complete for a predefined interval and terminate the corresponding word process after this interval.
I chose option 2 as I was dealing with other document types like PDF,PPT and I was too lazy to change the implementation! :)
来源:https://stackoverflow.com/questions/3207417/process-start-with-useshellexecute-true-doesnt-return-for-corrupt-word-docu