2011-04-13 82 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