I'm executing an external method SaveCurrentDocument()
via C# Interop that is blocking. That method pops up a dialog box asking users to "Save As". I need to automatically type something into this window and press OK. My problem is the method is blocking. So I cannot do the following:
SaveCurrentDocument(); // this is blocking
SendKeys(savePath);
SendKeys("{ENTER}");
How do I forcibly return control from a blocking method? My current plan was to start a BackgroundWorker
and execute the method within its callback, thereby blocking the worker but not my main thread. Is there a better way?
I don't think you can break a blocking call from within the same thread in C#. The problem is, BackgroundWorker's CancelAsync() doesn't actually stop the worker, or its current method, it sends a signal that the activity should be stopped, and if you're in an interop blocking call, you're not going to get through.
While not ideal, you could delegate the interop call to a separate thread from within the BackgroundWorker, while keeping the handle to it handy. Unfortunately, I know next to nothing about SendKeys, so I can't help you there.
That said, as M. Francis pointed out, you're probably best off checking if you can get a C# solution to writing the file (if it's a standard format like xlsx, docx, pdf, xml, or a fairly large collection of others), and using standardized solutions to saving the file.