Frage

I have a c# application that is opening a word document, running a .bas macro, and closing word. All of that works fine. The macro generates 2 message box dialogs with the result of the macro. I want to communicate these messages to my c# application. How can I do this?

Here is my code:

        // Object for missing (or optional) arguments.
        object oMissing = System.Reflection.Missing.Value;

        // Create an instance of Word, make it visible,
        // and open Doc1.doc.
        Word.Application oWord = new Word.Application();
        oWord.Visible = true;
        Word.Documents oDocs = oWord.Documents;
        object oFile = @"c:\\Macro.docm";

        // Open the file.
        Word._Document oDoc = oDocs.Open(ref oFile, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing, ref oMissing, ref oMissing,
            ref oMissing, ref oMissing);

        // Run the macro.
        oWord.GetType().InvokeMember("Run",
        System.Reflection.BindingFlags.Default |
        System.Reflection.BindingFlags.InvokeMethod,
        null, oWord, new Object[] { "MyMacro" });

        // Quit Word and clean up.
        oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oDoc);
        oDoc = null;
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oDocs);
        oDocs = null;
        oWord.Quit(ref oMissing, ref oMissing, ref oMissing);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
        oWord = null;

        return "all done!";
War es hilfreich?

Lösung

The solution I've used in the past for this is not for the faint of heart. It basically involves using good old fashioned Windows API calls to find the message box then to enumerate through its "windows" (controls) until you find the control with the text you are after.

If the message box always has the same title, you should be able to locate the window using the API call FindWindowEx. Once you have its window handle you can use EnumChildWindows to run through its controls until you find the one you are after. You can usually qualify the right control with either GetWindowText or GetClassName or a combination of both. Generally the text of a control should be available with GetWindowText, but I dont know what control MS used for this particular window.

Good luck!

FindWindowEx example

EnumChildWindows example

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top