怎么样才能获得word的 保存事件,并且屏蔽其执行让其执行自己的函数?

张群区块链
业界专家认证
2004-12-14 10:37:56
如题
我想取消word的保存功能,换成自己的保存函数。另外我在让word执行自己的函数时出现“由于宏安全设置,无法找到宏或宏被禁用”应该怎么解决?
高分求助,分数不够可以再加,500分之内可提。
...全文
253 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
张群区块链 2004-12-17
  • 打赏
  • 举报
回复
我已经解决了,使用的是带事件的变量声明。今天来了看到正如楼上哥们的办法。
虽然是自己解决的,但是还是要感谢两位朋友,以分为谢
techgopher 2004-12-17
  • 打赏
  • 举报
回复
捕捉application对象的DocumentBeforeSave事件,在里面做你的保存操作并把Cancel设为true不行吗?如果适用的话,在文档或模版里插入以下代码来重载Word内置的FileSave命令更简单:
Sub FileSave
'作自定义的保存操作
End Sub
张群区块链 2004-12-16
  • 打赏
  • 举报
回复
大哥,你真厉害,我先攻克那些英文的~
gjd111686 2004-12-15
  • 打赏
  • 举报
回复
文档
http://www.codeguru.com/Cpp/COM-Tech/activex/tutorials/article.php/c2629
gjd111686 2004-12-15
  • 打赏
  • 举报
回复
例子
http://www.codeguru.com/code/legacy/activex/wordauto.zip
cslf 2004-12-15
  • 打赏
  • 举报
回复
top,
gjd111686(数字金刚)继续!
gjd111686 2004-12-14
  • 打赏
  • 举报
回复
由CCmdTarget派生你自己的事件处理[Automation]
MsWord9__Application pApplication;
pApplication=pDoc.GetApplication();
static const GUID IID_IMsWord9ApplicationEventSink={0x000209f7,0x000,0x0000,{0xc0,0x00,0x0,0x00,0x00,0x00,0x00,0x46}};
IConnectionPointContainer *pConnPtContainer;
HRESULT hResult=pApplication.m_lpDispatch->QueryInterface(IID_IConnectionPointContainer,(void **)&pConnPtContainer);
if(SUCCEEDED(hResult))
{
hResult=pConnPtContainer->FindConnectionPoint(IID_IMsWord9ApplicationEventSink,&pConnectionPoint);
if(SUCCEEDED(hResult))
{
LPUNKNOWN pUnk=m_DefineOfficeEventSink.GetInterface(&IID_IUnknown);//m_DefineOfficeEventSink为你创建的处理类
hResult=pConnectionPoint->Advise(pUnk,&m_Advise);
if(SUCCEEDED(hResult))
{
//AfxMessageBox(_T("事件绑定成功!"),MB_ICONINFORMATION);
}
pConnPtContainer->Release();
}
}
pApplication.DetachDispatch();
pApplication.ReleaseDispatch();
以下是你的类
BEGIN_DISPATCH_MAP(CDefineOfficeEventSink, CCmdTarget)
//{{AFX_DISPATCH_MAP(CDefineOfficeEventSink)
// NOTE - the ClassWizard will add and remove mapping macros here.
DISP_FUNCTION_ID(CDefineOfficeEventSink,"Quit",2,OnQuit,VT_EMPTY,VTS_NONE)
//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()

// Note: we add support for IID_IDefineOfficeEventSink to support typesafe binding
// from VBA. This IID must match the GUID that is attached to the
// dispinterface in the .ODL file.

// {239235E6-EC2F-42BB-AD36-0E5CDB6A00CD}
static const IID IID_IDefineOfficeEventSink =
{ 0x000209f7, 0x000, 0x0000, { 0xc0, 0x00, 0x0, 0x00, 0x00, 0x00, 0x00, 0x46 } };

BEGIN_INTERFACE_MAP(CDefineOfficeEventSink, CCmdTarget)
INTERFACE_PART(CDefineOfficeEventSink, IID_IDefineOfficeEventSink, Dispatch)
END_INTERFACE_MAP()
void CDefineOfficeEventSink::OnQuit()
{
//AfxMessageBox(_T("Word.Application Quit Event Sink."),MB_ICONINFORMATION);
MessageBox(NULL,_T("退出未处理后果自负!"),_T("TelStar Office Word在线组件"),MB_ICONASTERISK);
}
张群区块链 2004-12-14
  • 打赏
  • 举报
回复
大哥,英文好 poor 啊我~
gjd111686 2004-12-14
  • 打赏
  • 举报
回复
http://support.microsoft.com/kb/309301/EN-US/
gjd111686 2004-12-14
  • 打赏
  • 举报
回复
HOWTO: Create a Sink Interface in MFC-Based COM Client
Article ID : 181845
Last Review : July 30, 2003
Revision : 1.0
This article was previously published under Q181845
On this Page
SUMMARY
MORE INFORMATION
REFERENCES

Note Microsoft Visual C++ .NET (2002) supports both the managed code model that is provided by the Microsoft .NET Framework and the unmanaged native Microsoft Windows code model. The information in this article applies only to unmanaged Visual C++ code.
SUMMARY
Microsoft Foundation Classes (MFC) has wizard support to add sink interfaces for ActiveX controls. However, this support does not extend to other COM servers. This article describes how to add a sink interface in an MFC client for source interfaces described by COM servers. Please note that this article applies to source interfaces, which are dispinterfaces, or dual interfaces with events being called through IDispatch::Invoke().
MORE INFORMATION
Here are the steps to add a sink interface to a COM client: 1. Using the Class Wizard, add a CCmdTarget derived object (for example, CMySink) with automation support. In the Class Wizard, select the Automation option rather than "Createable by type ID" option when adding this class.

NOTE: If you are using Visula Studio.NET do the following:

On the Project menu, select Add Class. In Add Class Dialog, select MFC Class.In MFC Class Wizard, on the Names page, under the base class, select CCmdTarget, and then under select support for automation, select Automation.
2. In the interface map, change the IID (the second parameter in the INTERFACE_PART macro) so that it is the IID of the source interface (usually the interface with the default and/or source attribute in the server's .idl file). The .idl file can be seen by viewing the typelib in the OLE/COM Object Viewer.
3. In the DISPATCH_MAP of CMySink class, add a DISP_FUNCTION_ID macro for each of the events defined in the source interface that you want to handle. For example: BEGIN_DISPATCH_MAP(CMySink, CCmdTarget)
DISP_FUNCTION_ID(CMySink,"Quit",2,OnObjQuit,VT_EMPTY,VTS_I4 VTS_I4)
END_DISPATCH_MAP()

The code above is an entry for handling the Quit event with a DISPID 2, which takes two long parameters and returns a void. OnObjectQuit is a CMySink member function that takes two longs and returns a void. This function must be added manually and is called when the COM server fires a Quit event.
4. Now you have hooked up the sink interface with the server so that you can start receiving events. To do this, call the AfxConnectionAdvise() function once the server object is created. For example: //Instantiate the sink class and hold a pointer to it.
m_pSink = new CMySink();

//Get a pointer to sinks IUnknown, no AddRef. CMySink implements only
//dispinterface and the IUnknown and IDispatch pointers will be same.
LPUNKNOWN pUnkSink = m_pSink->GetIDispatch(FALSE);

//Establish a connection between source and sink.
//m_pUnkSrc is IUnknown of server obtained by CoCreateInstance().
//m_dwCookie is a cookie identifying the connection, and is needed
//to terminate the connection.
AfxConnectionAdvise(m_pUnkSrc, IID_MYEVENT, pUnkSink, FALSE,
&m_dwCookie);


5. When you have finished using the server object you need to terminate the connection before releasing the server object. You do this by calling the AfxConnectionUnadvise() function. For example: //Get a pointer to sinks IUnknown, no AddRef.
LPUNKNOWN pUnkSink = m_pSink->GetIDispatch(FALSE);

//Terminate a connection between source and sink.
//m_pUnkSrc is IUnknown of server obtained by CoCreateInstance().
//m_dwCookie is a value obtained through AfxConnectionAdvise().
AfxConnectionUnadvise(m_pUnkSrc, IID_MYEVENT, pUnkSink, FALSE,
m_dwCookie);


Because CMySink was created on the heap, make sure you delete it to avoid memory leaks.
REFERENCES
The sink component of the Connpts.exe sample illustrates implementation of the sink interface.

For additional information, please see the following article in the Microsoft Knowledge Base:
152087 SAMPLE: Connpts.exe Implements Connection Points in MFC Apps
gjd111686 2004-12-14
  • 打赏
  • 举报
回复
http://support.microsoft.com/kb/181845/EN-US/
gjd111686 2004-12-14
  • 打赏
  • 举报
回复

First, add a new class CWordEventSink deriving from CCmdTarget (setting the automation check box). We will use this class as a sink for both the application events and the document events. Here is the include file (without the unrelevant code for the discussion here).


const IID IID_IWordAppEventSink = __uuidof(Word::ApplicationEvents);
const IID IID_IWordDocEventSink = __uuidof(Word::DocumentEvents);

class CWordEventSink : public CCmdTarget
{
public:
CWordEventSink();
virtual ~CWordEventSink();
protected:

// Generated OLE dispatch map functions
//{{AFX_DISPATCH(CWordEventSink)
afx_msg void OnAppStartup();
afx_msg void OnAppQuit();
afx_msg void OnAppDocumentChange();
afx_msg void OnDocNew();
afx_msg void OnDocOpen();
afx_msg void OnDocClose();
//}}AFX_DISPATCH
};

Not too complicated indeed. You just see the methods that will be called by the message dispatching of the CCmdTarget class based on the dispatch map defined in the source file. So, here is a part of the source file (with only one of the event handler shown) :


BEGIN_DISPATCH_MAP(CWordEventSink, CCmdTarget)
//{{AFX_DISPATCH_MAP(CWordEventSink)
DISP_FUNCTION(CWordEventSink, "Startup",OnAppStartup,VT_EMPTY, VTS_NONE)
DISP_FUNCTION(CWordEventSink, "Quit",OnAppQuit,VT_EMPTY, VTS_NONE)
DISP_FUNCTION(CWordEventSink, "DocumentChange", OnAppDocChange,VT_EMPTY, VTS_NONE)
DISP_FUNCTION(CWordEventSink, "New",OnDocNew,VT_EMPTY, VTS_NONE)
DISP_FUNCTION(CWordEventSink, "Open",OnDocOpen,VT_EMPTY, VTS_NONE)
DISP_FUNCTION(CWordEventSink, "Close",OnDocClose,VT_EMPTY, VTS_NONE)
//}}AFX_DISPATCH_MAP
END_DISPATCH_MAP()

BEGIN_INTERFACE_MAP(CWordEventSink, CCmdTarget)
INTERFACE_PART(CWordEventSink, IID_IWordAppEventSink, Dispatch)
INTERFACE_PART(CWordEventSink, IID_IWordDocEventSink, Dispatch)
END_INTERFACE_MAP()

void CWordEventSink::OnAppQuit()
{
AfxMessageBox("AppQuit event received");
}

The first three entries in the dispatch map are for the ApplicationEvents interface and the next three are for the DocumentEvents interface. Pay attention here to a trick of class Wizard : DISP_FUNCTION uses successively dispids beginning with 1, which matches exactly the dispids of events fired by Word (Startup has dispid 1, New has dispid 4 for example as you can check in the tlb). If not the case, you should use entries like :


DISP_FUNCTION_ID(CWordEventSink, "Quit", 0x02, OnAppQuit, VT_EMPTY, VTS_NONE)

Unfortunately, it seems that class wizard doesn't support this notation. Shocking !

You just need to have an instance of this CWordEventSink class but you won't receive events yet because you still have to connect your sink class to Word (how could Word know that you would like to receive these events). This is generally done with the AfxConnectionAdvise and AfxConnectionUnadvise functions but I will present another more object oriented way to do it. The basic functionnality to connect and disconnect a sink is encapsulated in a class called CConnectionAdvisor. Here is the include file :
class CConnectionAdvisor
{
public:
CConnectionAdvisor(REFIID iid);
BOOL Advise(IUnknown* pSink, IUnknown* pSource);
BOOL Unadvise();
virtual ~CConnectionAdvisor();

private:
CConnectionAdvisor();
CConnectionAdvisor(const CConnectionAdvisor& ConnectionAdvisor);
REFIID m_iid;
IConnectionPoint* m_pConnectionPoint;
DWORD m_AdviseCookie;
};

The constructor takes a reference to the interface you need to connect (IID_IWordAppEventSink or IID_IWordDocEventSink in the example). You call Advise when you need to connect your Sink to the given interface in the Source (that is Word) and Unadvise to disconnect. The implementation of Advise is very similar to the AfxConnectionAdvise but we keep a pointer to the IConnectionPoint interface to make the implementation of Unadvise easier. If you forget to disconnect, the destructor will take care of it. Here is the implementation :


CConnectionAdvisor::CConnectionAdvisor(REFIID iid) : m_iid(iid)
{
m_pConnectionPoint = NULL;
m_AdviseCookie = 0;
}

CConnectionAdvisor::~CConnectionAdvisor()
{
Unadvise();
}

BOOL CConnectionAdvisor::Advise(IUnknown* pSink, IUnknown* pSource)
{
// Advise already done
if (m_pConnectionPoint != NULL)
{
return FALSE;
}

BOOL Result = FALSE;

IConnectionPointContainer* pConnectionPointContainer;

if (FAILED(pSource->QueryInterface(
IID_IConnectionPointContainer,
(void**)&pConnectionPointContainer)))
{
return FALSE;
}

if (SUCCEEDED(pConnectionPointContainer->FindConnectionPoint(m_iid, &m_pConnectionPoint)))
{
if (SUCCEEDED(m_pConnectionPoint->Advise(pSink, &m_AdviseCookie)))
{
Result = TRUE;
}
else
{
gjd111686 2004-12-14
  • 打赏
  • 举报
回复
Automation And Eventing With Microsoft Word

--------------------------------------------------------------------------------
This article was contributed by Christian Staffe.
In this article, I demonstrate several topics related to Word automation in MFC :

How to run Word 97 using automation from an MFC client using the #import compiler directive.
How to use the wrapper functions generated by #import to simply add a new document and make Word visible to the user.
How to catch and use the exceptions generated by the wrapper classes.
How to create a Sink interface in your client to catch the application and document events fired by Word using the connection point technology.
How to connect your Sink interface to the connection points in Word.
How to retrieve the built-in document properties of a Word Document.
Almost all topics presented here can be easily extended to any application exposing an automation interface and its type library.

The complete example is a dialog-based MFC application provided as a zip file compiled with Visual Studio 6.0. If you run it, you will be presented a dialog box with two buttons : "Run Word" and "Cancel". If you push "Run Word", an instance of word is started and a new document created. You can experiment by directly quitting Word, issuing a new document command. Note that the event handlers display message boxes on the screen and during this time, Word will not be responding (the event are fired synchronously), so you will have to switch to the test program and answer the message box before you can continue. When the Close Document event is received, the number of pages in the document is computed and displayed in the message box (Just press several CTRL ENTER to insert new pages before leaving Word and you will see the page count incrementing). When you quit Word, the event will be trapped and the application terminated. If you push "Cancel" after Word has been started, the application will terminate Word before killing itself.

Information concerning Word automation can be found in the following Microsoft Knowledge Base articles :

Q181845 : Create a Sink Interface in MFC-Based COM client
Q183599 : Catch Microsoft Word97 Application Events Using VC++
Q152087 : Connpts.exe Implements Connection Poitns in MFC Apps
Q179494 : Use Automation to Retrieve Built-in Document Properties
Q183369 : Use Automation to Run a Word 97 Macro with Arguments
The examples provided by Microsoft are generally quite old, not very comprehensive (at least for me), not really object oriented and do not use the new #import directive but rather the MFC ColeDispatchDriver class. I hope I succeeded in making these examples clearer. However, I won't explain all the COM stuff and the connection point technology. There are a lot of sources for this.

Now, let's stop talking, it's time for a little code (ok, ok, in a few lines, I promise) !

First you need Word97 installed on your machine and find the type library. For Word97, it's installed in C:\Program Files\Microsoft Office\Office (look for msword8.olb). In addition, you will need mso97.dll and vbeext1.olb (this one is located in C:\Program Files\Common Files\Microsoft Shared\VBA). If you ask why you need the two other files in addition to the Word97 type library, look in the msword8.tlh (more on this later) file generated by the #import directive and you will see a comment informing you that these are cross-referenced type libraries needed by msword8.olb. Now that you have all these files, here is the code to generate the wrapper classes.

#pragma warning (disable:4146)
#import "mso97.dll"
#pragma warning (default:4146)
#import "vbeext1.olb"
#import "msword8.olb" rename("ExitWindows", "WordExitWindows")

You need the pragma to avoid warning messages generated by the office97 type library. The compiler will generate two files (with extensions tlh and tli) for each #import. Using Visual Studio 6.0, you won't really need to look at these wrapper thanks to the automatic statement completion. Let's just say that these classes are smart pointers around the interfaces provided by Word.

Now that you have these wrapper classes, you can start Word as an automation server, add a new document and make it visible to the user with the following code :


Word::_ApplicationPtr m_pWord;
Word::_DocumentPtr m_pDoc;

try
{
HRESULT hr = m_pWord.CreateInstance(__uuidof(Word::Application));
ASSERT(SUCCEEDED(hr));

m_pDoc = m_pWord->Documents->Add();
m_pWord->Visible = VARIANT_TRUE;
}
catch (_com_error& ComError)
{
DumpComError(ComError);
}

void DumpComError(const _com_error& e)
{
CString ComErrorMessage;
ComErrorMessage.Format("COM Error: 0x%08lX. %s",e.Error(), e.ErrorMessage());
AfxMessageBox(ComErrorMessage);
}

Easy, no ? You first declare two smart pointers : one for the _Application interface and another one for the _Document interface. The #import has added Ptr at the end to indicate the smart pointer. __uuidof allows you to retrieve the CLSID of the Word.Application object which is the "entry point" to the Word object model (do not confuse _Application which is an interface with Application which is the coclass). You can easily add a new document and make the Word application visible to the user by calling the Visible property (this VB-like property mechanism is made possible thanks to the __declspec(property) specifier).

You will have noted the try/catch blocks. The wrapper functions you called transformed the COM errors from HRESULT to exceptions of type _com_error (you can avoid this by calling raw functions also provided by the wrapper). You can display the hresult and some "user friendly" error message contained in the exception using the DumpComError function.

Well, finished with the first three topics. Now, let's dive into the more interesting part : the connection points and events. Events can be fired by Word either at the application level or at the document level (look in the tli file or use the OLE/COM object viewer and search for the ApplicationEvents and DocumentEvents outgoing interfaces). You have 3 methods in the ApplicationEvents interface (Startup, Quit and DocumentChange) and 3 in the DocumentEvents interface (New, Open and Close). Before you can catch events in your MFC client, you need first to add a sink interface that will receive the events and connect your sink interface to Word.

5,139

社区成员

发帖
与我相关
我的任务
社区描述
其他开发语言 Office开发/ VBA
社区管理员
  • Office开发/ VBA社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧