2011-04-13 72 views
3

我在Delphi中使用TWordApplication。我的应用程序打开word的新实例,并在其文档上做些事情。问题是当我第一次运行我的应用程序,然后打开真正的word exe。 Word EXE没有打开新的单词实例,但链接到我的应用程序实例。所以,当我的应用程序写入其文档时,所有文本都显示在用户可见的exe文字上。TWordApplication和Word碰撞

WordApp := TWordApplication.Create(nil); 
WordApp.ConnectKind := ckNewInstance; 
(WordApp.Documents.Add(EmptyParam,EmptyParam,EmptyParam, varFalse)); 

然后用户手动打开Word。

WordApp.Selection.Text := 'test test test'; 

并且用户在手动打开的Word中看到'test test test'。

如果我第一次手动打开Word并启动我的应用程序一切正常。

回答

2

请确保您使用

WordApp.ConnectKind := ckNewInstance; 

打开您的Word应用程序。要么在代码中执行(如上所述),要么在设计时设置属性。这可确保您始终运行Word的新实例,并且除非您明确地使其可见,否则它将保持隐藏状态。 任何打开Word的用户将总是得到Word的另一个实例,并且不会看到您对文档放置了什么(除非您保存了它并打开了保存的文档)。

从DOC:

设置ConnectKind指示 ConnectKind组件如何建立 连接。当应用程序调用Connect(连接) (或ConnectTo)方法时,ConnectKind在应用程序运行时(如果AutoConnect为True,则为true)或 建立 连接。

下表列出了可能的值:

//Value    Meaning 
//ckRunningOrNew  Attach to a running server or create a new instance of the server. 
//ckNewInstance  Always create a new instance of the server. 
//ckRunningInstance Only attach to a running instance of the server. 
//ckRemote    Bind to a remote instance of the server. When using this option, 
//      you must supply a value for RemoteMachineName. 
//ckAttachToInterface Don't bind to the server. Instead, the application supplies an 
//      interface using the ConnectTo method, which is introduced in 
//      descendant classes. This option can't be used with the AutoConnect 
//      property. 

更新

其实,打开Word可以打开了一个不同的实例(这就是我记得它D5 /的Word97)但是目前Word确实重新使用应用程序打开的实例。所以为了避免“抓住用户手动打开的word文档”,你确实需要避免按照The_Fox的回答使用ActiveDocument。

+0

我设置它。但不是重点。 Iam开始我的应用程序。新实例已创建。我开始出现Word.exe和Word窗口。和Word.exe没有启动新的实例。所以我的应用程序在Word窗口中写入。 – userbb 2011-04-13 12:59:21

+0

然后,正如我在对您的问题的评论中所说:显示您的代码。如果你没有告诉我们你到底在做什么,我们不是克莱尔沃伊泰克,并且不能帮助你。用户如何启动Word?点击快捷方式或双击文档? – 2011-04-13 13:02:06

+0

对不起,我没有提交该评论...问题仍然存在:请向我们展示您的代码。 – 2011-04-13 13:18:32

4

这是Word的默认行为,它使用正在运行的实例。你必须做的是存储你想修改的文档的引用。所以不要使用ActiveDocument,而是使用你存储的Document。因为不能保证ActiveDocument是您认为它的文档。

//starting Word 
var 
    App: TWordApplication; 
    Doc: WordDocument; 
begin 
    App := TWordApplication.Create(nil); 
    Doc := App.Documents.AddOld(EmptyVar, EmptyVar); //open new document 

<..somewhere else..> 
    //modifying Word 
    Doc.DoWhateverIWant; // <--see? no ActiveDocument, so you are not 
         //    modifying the users doc 
+0

+1无论Word如何打开,启动或连接,这确实是避免“刮擦”整个当前可见文档的方式,无论哪一个可能是... – 2011-04-13 14:00:50

+0

虽然我不确信Word重新使用运行*隐藏*实例...(还有:-) – 2011-04-13 14:01:44

+0

现在相信。不要这样记住(D5/Word97),但Word(2007)现在肯定会重新使用甚至是由应用程序打开的隐藏实例... – 2011-04-13 17:11:27