Word, DocumentBeforeClose event, unable to Cancel event

  • Thread starter Thread starter AP
  • Start date Start date
A

AP

Hi,

I'm trying to use c# to pop up a dialog box when a user attempts to close
word to prompt them if they want to exit or cancel (obviously other stuff
needs to happen based on their selection but that's the gist of it.)
I have everything set up, and it seems to work except that setting Cancel to
true and returning from my c# method appears to do nothing. Word still
closes. Am I doing something wrong?

private void wa_DocumentBeforeClose(Document Doc, ref bool Cancel) {


DialogResult dr =

MessageBox.Show("Update Template File on the Server?","Update Template
File",MessageBoxButtons.YesNoCancel,MessageBoxIcon.Question,MessageBoxDefaul
tButton.Button1);


//If they cancel go back to word

if (dr == DialogResult.Cancel) {

Cancel = true;

return;

//word still closes

}

//If they say yes upload to server

if (dr == DialogResult.Yes) {

//do yes stuff

}


//NO - do nothing except

}


Adam
 
ISSUE
=====
You have a VS.NET 2003 application which automates Word.
When you set the Cancel parameter of the
DocumentBeforeClose event it is ignored.

CAUSE
======
The way the interfaces are defined in Word typelibrary
have the cancel parameter as [in] parameter. Something
like this:

interface IWorkbookEvents : IDispatch {
....
HRESULT _stdcall BeforeSave([in] VARIANT_BOOL* Cancel);

When interop assemblies are created they are based on the
typelib and they have this parameter defined in the same
way: [in]bool& Cancel
CLR 1.1 enforces that [in] params even as pointer are not
to be marshalled back to the caller. As this was not
enforced in CLR 1.0 the cancel parameter worked with
VS.NET 2002.

RESOLUTION
===========
Steps to resolve the issue:

1. Open WordTest (the one without the PIAs) in VS.NET 2003.
2. Make sure that Cancel parameter is ignored and that
the Project is
using the interop assemblies in your project's bin
folder. Now Close the
project.
3. Open VS.NET command prompt change directory to
C:\<project
folder>\bin\Debug..
4. Run this command:
ildasm /source interop.word.dll /out=interop.word.il
--This will create interop.word.il file
5. Open this file in notepad. Replace all instance of
[in] bool& Cancel

with

[in][out] bool& Cancel

6. Save the il file
7. Run the following command:
ilasm /dll interop.word.il /out=interop.word.dll
or
ilasm /dll
interop.word.il /out=interop.word.dll /key=filename.snk
(If you want your assembly to be signed)

8. Now open the WordTest project again. Remove the
reference to word and
add reference to the new interop.word.dll manually.
9. Rebuild the project. Run the application. This should
take care of
this issue and issues with all the other Cancel
parameters.
 
Back
Top